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?
代码
Approach #1 Recursive Approach
Complexity Analysis
Time complexity : O(n)
Space complexity : The worst case space required is O(n), and in the average case it's O(logn) where n is number of nodes.
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */classSolution {publicList<Integer> inorderTraversal(TreeNode root) {List<Integer> res =newArrayList<>();dfs(root, res);return res; }publicvoiddfs(TreeNode root,List<Integer> res) {if (root !=null) {if (root.left!=null) {dfs(root.left, res); }res.add(root.val);if (root.right!=null) {dfs(root.right, res); } } }}
Approach #2 Iterating method using stack
Complexity Analysis
Time complexity : O(n)
Space complexity : O(n)
1. Push the left node first
2. Pop and visit the value
3. Try to move to the right node
classSolution { pulic List<Integer> inorderTraversal(TreeNode root) {List<Integer> res =newArrayList<>();Stack<TreeNode> stack =newStack<>();TreeNode curr = root;while (curr !=null||!stack.isEmpty()) {// 1. Push the left node firstwhile (curr !=null) {stack.push(curr); curr =curr.left; }// 2. Pop and visit the value curr =stack.pop();res.add(curr.val);// 3. Try to move to the right node curr =curr.right; }return res; }}
Approach #3 Morris Traversal
Step 1: Initialize current as root
Step 2: While current is not NULL,
Complexity Analysis
Time complexity : O(n)
Space complexity : O(n)
If current does not have left child
a. Add current’s value
b. Go to the right, i.e., current = current.right
Else
a. In current's left subtree, make current the right child of the rightmost node
b. Go to this left child, i.e., current = current.left