[leetcode] 94. 二叉树的中序遍历

94. 二叉树的中序遍历

中序遍历
递归写法

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        dfs(root, list);
        return list;
    }

    public void dfs(TreeNode node, List<Integer> ans) {
        if (node.left != null) dfs(node.left, ans);
        ans.add(node.val);
        if (node.right != null) dfs(node.right, ans);
    }
}

非递归写法

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return list;
        Stack<TreeNode> stack = new Stack<>();

        while (!stack.isEmpty() || root != null) {
            while (root != null) {
                stack.add(root);
                root = root.left;
            }
            if (!stack.isEmpty()) {
                root = stack.pop();
                list.add(root.val);
                root = root.right;
            }
        }

        return list;
    }
}
posted @ 2018-08-07 22:22 ACBingo 阅读(...) 评论(...) 编辑 收藏