【二叉树】94.二叉树的中序遍历

题目
重点掌握迭代版遍历

法1:迭代版遍历

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        if (root == null) {
            return res;
        }
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || stack.size() > 0) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                TreeNode tmp = stack.pop();
                res.add(tmp.val);
                root = tmp.right;
            }
        }

        return res;
    }
}

法2:递归版遍历

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        fun(root, res);
        return res;
    }

    public void fun(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        fun(root.left, res);
        res.add(root.val);
        fun(root.right, res);
    }
}

你可能感兴趣的:(力扣Top100,二叉树遍历)