二叉树--先序遍历的递归和非递归(leetcode 144

非递归解法

递归解法比较简单,是考察概念,放在文章末尾来说。

用递归方法能解决的问题都能用非递归方法来实现,因为递归方法无非就是用函数栈来保存信息,如果用自己申请的数据结构来代替函数栈,也可以实现一样的功能

步骤:

1.申请一个栈,将头节点head压入栈中

2.从stack中弹出结点,记为temp,打印temp。先将右节点压入栈(如果有的话),再将左结点压入栈(如果有的话)

3.不断重复步骤2,直至stack为空

代码:

    public List<Integer> preorderTraversal(TreeNode root) {
        Stack<TreeNode> stack = new Stack<> ();
        List<Integer> list = new ArrayList<> ();
        if (root == null) {
            return list;
        }
        stack.push(root);
        while (!stack.isEmpty()){
            TreeNode temp = stack.pop();
            list.add(temp.val);
            if (temp.right != null){
                stack.push(temp.right);
            }
            if (temp.left != null){
                stack.push(temp.left);
            }
        }
        return list;
    }

递归解法

    List<Integer> list = new ArrayList<Integer> ();

    public List<Integer> preorderTraversal(TreeNode root) {
        if (root == null){
            return list;
        }
        list.add(root.val);
        preorderTraversal(root.left);
        preorderTraversal(root.right);
        return list;
    }

猜你喜欢

转载自www.cnblogs.com/swifthao/p/13211016.html