public class TreeNode{
int val;
TreeNode left;
TreeNode right;
TreeNode(int val){
this.val = val;
}
}
一、二叉树的前序遍历
//非递归实现
public void preOrder(TreeNode root){
if(root == null) return;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.isEmpty()){
TreeNode node = stack.pop();
System.out.println(node.val);
//因为栈是先进后出,所以先压右孩子,再压左孩子
if(node.right != null){
stack.push(node.right);
}
if(node.left != null){
stack.push(node.left);
}
}
}
//递归实现
public void preOrder(TreeNode root){
if(root == null) return;
System.out.println(root.val);
preOrder(root.left);
preOrder(root.right);
}
二、二叉树的后序遍历
//非递归实现
//压栈的顺序 从上而下,先左后右, 出栈 从下而上, 先右后左, 借助一个辅助栈
public void postOrder(TreeNode root){
if(root == null) return;
Stack<TreeNode> s1 = new Stack<>();
Stack<TreeNode> s2 = new Stack<>();
s1.push(root);
while(!s1.isEmpty()){
TreeNode node = s1.pop();
s2.push(node);
if(node.left != null)
s1.push(node.left);
if(node.right != null)
s1.push(node.right);
}
while(!s2.isEmpty()){
System.out.println(s2.pop().val + " "));
}
}
三、二叉树的中序遍历
public void inorder(TreeNode root){
if(root == null) return;
Stack<TreeNode> stack = new Stack<>();
TreeNode p = root;
ArrayList<Integer> list = new ArrayList<>();
while(!stack.isEmpty() || p != null){
while(p != null){
stack.push(p);
p = p.left;
}
p = stack.pop();
list.add(p.val);
p = p.right;
}
return list;
}