94. Binary Tree Inorder Traversal
94. 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?
Solution
-
☝️
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> res = new ArrayList<>();
while (root != null || !stack.empty()) {
while(root != null) {
stack.push(root);
root = root.left;
}
TreeNode node = stack.pop();
res.add(node.val);
root = node.right;
}
return res;
}
}

浙公网安备 33010602011771号