树的定义
public class TreeNode {
public TreeNode left;
public TreeNode right;
public int val;
public TreeNode(int val){
this.val=val;
this.left=null;
this.right=null;
}
}
前序遍历
public void preorderStack(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
System.out.println(root.val);
root=root.left;
}
root=stack.pop();
root=root.right;
}
}
public void preOrder(TreeNode root){
if(root!=null){
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
}
中序遍历
public void inorderStack(TreeNode root) {
Stack<TreeNode> stack=new Stack<>();
while(root!=null || !stack.isEmpty()){
while(root!=null){
stack.push(root);
root=root.left;
}
root=stack.pop();
System.out.println(root.val);
root=root.right;
}
}
public void inOrder(TreeNode root){
if(root!=null){
inOrder(root.left);
System.out.println(root.val);
inOrder(root.right);
}
}
后序遍历
public void postorderStack(TreeNode root){
Stack<TreeNode>stack=new Stack<>();
Map<TreeNode, Boolean> map=new HashMap<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node=stack.peek();
if(node.left!=null && !map.containsKey(node.left)){
node=node.left;
while(node!=null){
if(map.containsKey(node))break;
stack.push(node);
node=node.left;
}
continue;
}
if(node.right!=null && !map.containsKey(node.right)){
stack.push(node.right);
continue;
}
TreeNode t=stack.pop();
map.put(t, true);
System.out.println(t.val);
}
}
public void postOrder(TreeNode root){
if(root!=null){
postOrder(root.left);
postOrder(root.right);
System.out.println(root.val);
}
}