一、层序遍历
//层序遍历
public static void levelOrder(Node root){
if(root==null){
return;
}
//用队列来模拟
Queue<Node> queue=new LinkedList<>();
//先把根节点入队列
queue.offer(root);
while(!queue.isEmpty()){
//先打印根节点
Node cur=queue.poll();
System.out.print(cur.val+" ");
if(cur.left!=null){
//左子树
queue.offer(cur.left);
}
if(cur.right!=null){
//左子树
queue.offer(cur.right);
}
}
}
二、先序遍历
//先序遍历
public static void FirstOrder(Node root) {
if (root == null) {
return;
}
Stack<Node> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
Node cur = stack.pop();
System.out.print(cur.val + " ");
if (cur.right != null) {
stack.push(cur.right);
}
if (cur.left != null) {
stack.push(cur.left);
}
}
}
三、中序遍历
public static List<Character> inorderTraversalhko9(Node root){
List<Character> ret = new ArrayList<>();
Stack<Node> stack = new Stack<>();
Node cur = root;
while (cur != null || !stack.isEmpty()) {
while (cur != null) {
stack.push(cur);
cur = cur.left;
}
cur = stack.pop();
ret.add(cur.val);
cur = cur.right;
}
return ret;
}
四、后序遍历
//后序遍历
public static void postordertraversal(Node root) {
if(root==null){
return;
}
//用栈来模拟
Stack<Node> stack = new Stack<>();
Node prev=null;
Node cur=root;
//不断往左子树方向走,每走一次就将当前节点保存到栈中
//这是模拟递归的调用
while(true){
//把左子树全部入栈
while(cur!=null){
stack.push(cur);
cur=cur.left;
}
if(stack.isEmpty()) {
break;
}
//没有左子树了,那就取栈顶元素
Node top=stack.peek();
//看有没有右子树
if(top.right==null||top.right==prev){
System.out.print(top.val+" ");
stack.pop();
prev=top;
}else{
cur=top.right;
}
}
}