LeetCode94. 二叉树的中序遍历

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        /**
         * 方法1: 递归
         *      时间复杂度:O(n) 空间复杂度: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) {
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            res.add(root.val);
            root = root.right;
        }
        return res;
    }
    private void dfs(TreeNode root, List<Integer> res) {
        if (root == null) return;
        dfs(root.left, res); //
        res.add(root.val); //
        dfs(root.right, res); //
    }
}
原文地址:https://www.cnblogs.com/HuangYJ/p/14156840.html