二叉树遍历
https://www.cnblogs.com/zhi-leaf/p/10813048.html
前序遍历
访问顺序:先根节点,再左子树,最后右子树;上图的访问结果为:GDAFEMHZ。
中序遍历
访问顺序:先左子树,再根节点,最后右子树;上图的访问结果为:ADEFGHMZ。
后续遍历
访问顺序:先左子树,再右子树,最后根节点,上图的访问结果为:AEFDHZMG。
1)递归实现
package com.logan.Algo; import java.util.LinkedList; import java.util.Queue; import java.util.Stack; public class Traverse { //前序遍历,结果:GDAFEMHZ public void preOrderTraverse1(TreeNode root) { if(root != null) { System.out.println(root.val + "->"); preOrderTraverse1(root.left); preOrderTraverse1(root.right); } } public void preOrderTraverse2(TreeNode root) { Stack<TreeNode> stack = new Stack(); TreeNode node = root; while(node != null || !stack.empty()) { if(node != null) { System.out.println(node.val + "->"); stack.push(node); node = node.left; }else { TreeNode tem = stack.pop(); node = tem.right; } } } //中序遍历,结果:ADEFGHMZ public void inOrderTraverse1(TreeNode root) { if(root != null) { inOrderTraverse1(root.left); System.out.println(root.val + "->"); inOrderTraverse1(root.right); } } public void inOrderTraverse2(TreeNode root) { Stack<TreeNode> stack = new Stack<>(); TreeNode node = root; while(node != null || !stack.isEmpty()) { if(node != null) { stack.push(node); node = node.left; }else { TreeNode tem = stack.pop(); System.out.println(tem.val + "->"); node = tem.right; } } } //后续遍历,结果:AEFDHZMG public void postOrderTraverse1(TreeNode root) { if(root != null) { postOrderTraverse1(root.left); postOrderTraverse1(root.right); System.out.println(root.val + "->"); } } public void postOrderTraverse2(TreeNode root) { TreeNode cur, pre = null; Stack<TreeNode> stack = new Stack<>(); stack.push(root); while(!stack.isEmpty()) { cur = stack.peek(); if((cur.left == null && cur.right == null) || (pre != null && (pre==cur.left || pre ==cur.right))) { System.out.println(cur.val + "->"); stack.pop(); pre=cur; }else { if(cur.right != null) stack.push(cur.right); if(cur.left != null) stack.push(cur.left); } } } //层次遍历,结果:GDMAFHZE public void levelOrderTraverse(TreeNode root) { if(root == null) { return; } Queue<TreeNode> queue = new LinkedList<TreeNode>(); queue.add(root); while(!queue.isEmpty()) { TreeNode node = queue.poll(); System.out.println(node.val + "->"); if(node.left != null) { queue.add(node.left); } if(node.right != null) { queue.add(node.right); } } } }
心再坚强也不要独自飞翔