LeetCode144. 二叉树的前序遍历

思路1:递归。

思路2:非递归。使用栈模拟递归。

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        /**
         *方法1:递归
         *  时间复杂度O(n)
         *  空间复杂度O(n)为递归中栈的开销,平均情况为 O(logn),最坏情况下树呈现链状,为 O(n)
         */
        /*
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
        */
        /**
         * 方法2:非递归,使用栈模拟递归
         *      时间复杂度O(n)
         *      空间复杂度O(n)为迭代过程中显式栈的开销
         */
        List<Integer> res = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                res.add(root.val);
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            root = root.right;
        }
        return res;
    }
    private void dfs(TreeNode root, List<Integer> res) {
        if (root == null) return;
        res.add(root.val); //
        dfs(root.left, res); //
        dfs(root.right, res); //
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14156838.html