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?
一刷
題解:
樹(shù)的遍歷復(fù)習(xí): Pre-Order(root, left, right), In-Order(left, root, right), Post-Order(left, right, root)杀赢。總結(jié)湘纵,pre, in, post都是針對(duì)root的相對(duì)位置來(lái)說(shuō)的脂崔。
遞歸很簡(jiǎn)單:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
inorderTraversal(res, root);
return res;
}
private void inorderTraversal(List<Integer> res, TreeNode root){
if(root==null) return;
inorderTraversal(res, root.left);
res.add(root.val);
inorderTraversal(res, root.right);
}
}
嘗試iteratively,棧
public class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode node = root;
while(node!=null || !stack.isEmpty()){
if(node!=null){
stack.push(node);
node = node.left;
}
else{
node = stack.pop();//parent
res.add(node.val);
node = node.right;//iterate from the right
}
}
}
}