Description,
Given a binary tree, return the inorder traversal of its nodes’ values.
For example:
Given binary tree [1,null,2,3],
1
\
2
/
3
return [1,3,2].
Note: Recursive solution is trivial, could you do it iteratively?
Iterative using Stack
This is trivial. Visit the Tree traversal page for detailed guidance.
Tree traversal
Time complexity: O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
/**
* @solution: Iterative using stack.
* @timeComplexity: O(n)
* @runtime: 1ms
*/
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> ret = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
while (!stack.empty() || root != null) {
if (root != null) {
stack.push(root);
root = root.left;
} else { // pop "in" node of the tree
root = stack.pop();
ret.add(root.val);
root = root.right;
}
}
return ret;
}
}
Runtime: 1ms