1. 程式人生 > 實用技巧 >94. [二叉樹]二叉樹的中序遍歷

94. [二叉樹]二叉樹的中序遍歷

94. 二叉樹的中序遍歷

方法一:遞迴

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

方法二:迭代

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        LinkedList<TreeNode> stack = new LinkedList<>();

        while (root != null || !stack.isEmpty()){
            while(root != null){
                stack.offer(root);
                root = root.left;
            }
            root = stack.pollLast();
            ans.add(root.val);
            root = root.right;
        }
        return ans;
    }
}