【LeetCode】94. Binary Tree Inorder Traversal
Difficulty: Medium
More:【目录】LeetCode Java实现
Description
https://leetcode.com/problems/binary-tree-inorder-traversal/
Given a binary tree, return the inorder traversal of its nodes' values.
Example:
Input: [1,null,2,3] 1 \ 2 / 3 Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?
Intuition
1. Recursion
2. Iteration
Solution
Recursion
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new ArrayList<Integer>(); put(root, list); return list; } private void put(TreeNode node, List<Integer> list){ if(node==null) return; put(node.left, list); list.add(node.val); put(node.right, list); }
Iteration
public List<Integer> inorderTraversal(TreeNode root) { List<Integer> list = new LinkedList<>(); Stack<TreeNode> stk = new Stack<>(); while(root!=null || !stk.isEmpty()){ while(root!=null){ stk.push(root); root=root.left; } list.add(stk.peek().val); root = stk.pop().right; } return list; }
Complexity
Time complexity : O(n)
Space complexity : O(n)
More:【目录】LeetCode Java实现