Given a binary tree, return the inorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,3,2]
.
Note: Recursive solution is trivial, could you do it iteratively?
confused what "{1,#,2,3}"
means? > read more on how binary tree is serialized on OJ.
OJ's Binary Tree Serialization:
The serialization of a binary tree follows a level order traversal, where '#' signifies a path terminator where no node exists below.
Here's an example:
1 / \ 2 3 / 4 \ 5
The above binary tree is serialized as "{1,2,3,#,#,4,#,#,5}"
.
Note:
Binary Tree两边点是随机分布。Binary Search Tree是小的在左边,大的在右边。
Binary Tree Inorder Traversal是指先访问左subtree,再访问右subtree。
解决此题遇到的问题是每次访问到一个节点,怎样判断此节点的左subtree是否已被访问过?
建立new list时用到的是ArrayList类。Stack的操作除了push,pop,还有peek,即为获取栈顶数据,但并不弹出。
Solution 1:为每个添加一个boolean marker,来记录左孩子是否被访问过。
/**
* Definition for binary tree
* 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> solu = new ArrayList<Integer>();
if(root==null) return solu;
Stack<TreeNode> roots = new Stack<TreeNode>();
Stack<Boolean> leftChecked = new Stack<Boolean>();
roots.push(root);
leftChecked.push(false);
while(!roots.empty()){
TreeNode current = roots.peek();
boolean isChecked = leftChecked.peek();
if(current==null) {roots.pop(); leftChecked.pop();continue;}
if(current.left!=null && !isChecked) {
roots.push(current.left);
leftChecked.pop();
leftChecked.push(true);
leftChecked.push(false);
continue;
}
else{
solu.add(current.val);
roots.pop();
leftChecked.pop();
if(current.right!=null){
roots.push(current.right);
leftChecked.push(false);
continue;
}
}
}
return solu;
}
}
Solution 2: 根据Stack的特性,和Inorder traversal的特点,要求从树的最底端开始遍历,且先遍历左subtree。先往左走,将路径上的点都push入堆栈。当左subtree为null时,表示到达最底层,将stack栈顶数据pop出来,记下value,查看是否有右subtree。只有pop后才记住value,且pop后只往又走,因为在stack里的数据已经都被check过左subtree。
/**
* Definition for binary tree
* 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> solu = new ArrayList<Integer>();
Stack<TreeNode> path = new Stack<TreeNode>();;
while(!path.empty()||root!=null){
if(root!=null){
path.push(root);
root = root.left;
}
else{
root = path.pop();
solu.add(root.val);
root = root.right;
}
}
return solu;
}
}
第二种方法比较优化