一、层序遍历
层序遍历思路
- 先将树的根节点入队,
- 如果队列不空,则进入循环
- { 将队首元素出队,并输出它;
- 如果该队首元素有左孩子,则将其左孩子入队;
- 如果该队首元素有右孩子,则将其右孩子入队 }
public static void level(TreeNode head){
if (head==null){
return;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()){
TreeNode cur=queue.poll();
System.out.println(cur.val);
if (cur.left!=null){
queue.add(cur.left);
}
if(cur.right!=null){
queue.add(cur.right);
}
}
}
二、前序遍历
根据前序遍历的顺序,优先访问根结点,然后在访问左子树和右子树。所以,对于任意结点node,第一部分即直接访问之,之后在判断左子树是否为空,不为空时即重复上面的步骤,直到其为空。若为空,则需要访问右子树。注意,在访问过左孩子之后,需要反过来访问其右孩子,所以,需要栈这种数据结构的支持。对于任意一个结点node,具体步骤如下:
a)访问之,并把结点node入栈,当前结点置为左孩子;
b)判断结点node是否为空,若为空,则取出栈顶结点并出栈,将右孩子置为当前结点;否则重复a)步直到当前结点为空或者栈为空(可以发现栈中的结点就是为了访问右孩子才存储的)
public static void preOrder(TreeNode head) {
TreeNode node=head;
Stack<TreeNode> stack=new Stack<>();
while (node!=null||!stack.isEmpty()){
if (node!=null){
System.out.println(node.val);
stack.push(node);
node=node.left;
}else {
node=stack.pop();
node=node.right;
}
}
}
三、中序遍历
和前序遍历相同的道理。只不过访问的顺序移到出栈时
public static void inOrder(TreeNode head){
TreeNode node=head;
Stack<TreeNode> stack=new Stack<>();
while (node!=null||!stack.isEmpty()){
if (node!=null){
stack.push(node);
node=node.left;
}else {
node=stack.pop();
System.out.println(node.val);
node=node.right;
}
}
}
三、二叉树的后序遍历实现(基于两个栈实现)
具体思路:
- 准备两个栈栈S1 和S2 。首先根节点入栈S1。
- 当S1不为空弹出栈顶元素,并入栈S2,如果说弹出的左右子树不为空,则依次将其左子树和右子树入栈。直到栈S1空时停止。
- 然后输出栈S2,即为后续遍历的结果
public static void test(TreeNode head){
if (head==null){
return;
}
Stack<TreeNode> stack1=new Stack<>();Stack<TreeNode> stack2=new Stack<>();
stack1.push(head);
while (!stack1.isEmpty()){
TreeNode cur=stack1.pop();
stack2.push(cur);
if (cur.left!=null){
stack1.push(cur.left);
}if (cur.right!=null){
stack1.push(cur.right);
}
}while (!stack2.isEmpty()){
System.out.println(stack2.pop().val);
}
}