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

题目

链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal

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

示例:

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

输出: [1,3,2]

递归

class Solution {
    private List<Integer> ans = new ArrayList<>();

    public List<Integer> inorderTraversal(TreeNode root) {
        traversal(root);
        return ans;
    }

    private void traversal(TreeNode cur) {
        if (cur == null) 
            return;
        traversal(cur.left);
        ans.add(cur.val);
        traversal(cur.right);
    }
}

迭代

class Solution {
    private List<Integer> ans = new ArrayList<>();

    public List<Integer> inorderTraversal(TreeNode root) {
        if (root == null)
            return ans;
        LinkedList<TreeNode> stack = new LinkedList<>();
        stack.push(root);
        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (cur != null) {
                if (cur.right != null)
                    stack.push(cur.right);
                stack.push(cur);
                stack.push(null);
                if (cur.left != null)
                    stack.push(cur.left);
            } else {
                TreeNode node = stack.pop();
                ans.add(node.val);
            }
        }
        return ans;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13907085.html