二叉树遍历的常规算法是递归,通过一个栈可实现非递归算法,许多关于树的算法题都是这些非递归算法的变形,需要熟练掌握。
特别注意后序遍历的特殊性,在回溯时需要判断右子树是否已经访问过。
1、前序遍历
public void pre(TreeNode node) {
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = node;
while(cur!=null || !stack.isEmpty()) {
while(cur!=null){
System.out.println(cur.val);
stack.push(cur);
cur = cur.left;
}// 至此,到达最左下
if(!stack.isEmpty()){
cur = stack.pop().right;
}
}
}
2、中序遍历
public void mid(TreeNode node){
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = node;
while(cur!=null || !stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
if(!stack.isEmpty()){
cur = stack.pop();
System.out.println(cur.val);
cur = cur.right;
}
}
}
3、后序遍历
public void post(TreeNode node){
Stack<TreeNode> stack = new Stack<>();
TreeNode cur = node, record = null;
while(cur!=null || !stack.isEmpty()){
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
if(!stack.isEmpty()) {
cur = stack.peek();
if (cur.right != null && cur.right!=record) {
cur = cur.right;
} else {
System.out.println(cur.val);
stack.pop();
record = cur;
cur=null;
}
}
}
}