数据结构-树的非递归遍历
思路:由于递归和栈的原理都是一样的,故而可以才用栈来处理
前序
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
if(root==null) return list;
Stack<TreeNode> stack=new Stack<TreeNode>();
while(!stack.empty() ||root!=null){
while(root!=null){
list.add(root.val);
stack.push(root);
root=root.left;
}
root=stack.pop();
root=root.right;
}
return list;
}
}
中序
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
if(root==null) return list;
Stack<TreeNode> stack=new Stack<TreeNode>();
while(!stack.empty() ||root!=null){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
list.add(root.val);
root=root.right;
}
return list;
}
}
后序遍历
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer>();
if(root==null) return list;
TreeNode temp=null;
Stack<TreeNode> stack=new Stack<TreeNode>();
while(!stack.empty() ||root!=null){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
if(root.right==null || root.right==temp){
list.add(root.val);
temp=root;//避免循环重复录入左子树
root=null;
}else{
stack.push(root);
root=root.right;
}
}
return list;
}