LeetCode 94. Binary Tree Inorder Traversal 二叉树的中序遍历(Java)

题目:

Given a binary tree, return the inorder traversal of its nodes’ values.
LeetCode 94. Binary Tree Inorder Traversal 二叉树的中序遍历(Java)_第1张图片
Follow up: Recursive solution is trivial, could you do it iteratively?

解答:

二叉树的中序遍历,很基础的题目,递归方法比较简单,题目要求我们尝试用非递归的方式求解,则借助栈 stack 进行实现

解法一:递归

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        Recursive(root, res);
        return res;
    }
    private void Recursive(TreeNode root, List<Integer> res) {
        if(root == null) {
            return;
        }
        Recursive(root.left, res);
        res.add(root.val);
        Recursive(root.right, res);
    }
}

解法二:非递归

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

你可能感兴趣的:(LeetCode)