LeetCode算法题: 二叉树的前序遍历preorderTraversal

给定一个二叉树,返回它的 前序 遍历。

 示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [1,2,3]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-preorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

递归:

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if(root == null)
            return list;
        preOrder(root,list);
        return list;
    }
    private void preOrder(TreeNode root,List<Integer> list) {
        if(root == null)
            return;
        list.add(root.val); //根左右,先将root节点添加到list中
        preOrder(root.left,list);
        preOrder(root.right,list);
    }
}

迭代:利用辅助栈,首先不断向list加入root,root也要入栈,为的是得到root.right。

public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while(!stack.isEmpty() || root != null){
            while(root != null) {
                stack.push(root);
                list.add(root.val);
                root = root.left;
            }
            TreeNode cur = stack.pop();
            root = cur.right;
        }
        return list;
    }
发布了239 篇原创文章 · 获赞 70 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_43777983/article/details/103494663