非递归的binary tree traversal:
Inorder:
从根开始,首先沿着左边遍历,并把每个左节点添加到栈。当遍历到null时,从栈中释放一个节点,并访问节点。然后遍历该节点的右边, 直到栈中没有节点
/*;
* 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) {
ArrayList<Integer> list=new ArrayList<Integer>();
Stack<TreeNode> s=new Stack<TreeNode>();
TreeNode subroot=root;
TreeNode current=root;
while(!s.isEmpty()||current!=null){
while(current!=null){
s.push(current);
current=current.left;
}
current=s.pop();
list.add(current.val);
current=current.right;
}
return list;
}
}
preorder:
从根开始,首先沿着左边遍历,并把每个左节点添加到栈,不同的是当添加的时候访问该节点,这样父节点就在子结点之前访问。后面和inorder类似,遇到null的时候,从栈中释放,遍历其右子树。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
Stack<TreeNode> s=new Stack<TreeNode>();
ArrayList<Integer> list=new ArrayList<Integer>();
/*TreeNode current=root;
TreeNode subroot=root;
while(subroot!=null){
current=subroot;
while(current!=null){
list.add(current.val);
if(current.right!=null){
s.push(current.right);
}
current=current.left;
}
if(s.isEmpty()){
subroot=null;
}
else subroot=s.pop();
}*/
TreeNode current=root;
while(!s.isEmpty()||current!=null){
while(current!=null){
s.push(current);
list.add(current.val);
current=current.left;
}
current=s.pop();
current=current.right;
}
return list;
}
}