定义一个二叉树
// 定义一个二叉树
class TreeNode {
public int value;
public TreeNode left;
public TreeNode right;
public TreeNode(int value) {
this.value = value;
this.left = null;
this.right = null;
}
}
构造出一棵树供后面使用。
// 4
// / \
// 2 5
// / \
// 1 3
TreeNode treeNode = new TreeNode(4);
TreeNode treeNode1 = new TreeNode(2);
TreeNode treeNode2 = new TreeNode(1);
TreeNode treeNode3 = new TreeNode(3);
TreeNode treeNode4 = new TreeNode(5);
treeNode.left = treeNode1;
treeNode.right = treeNode4;
treeNode1.left = treeNode2;
treeNode1.right = treeNode3;
广度优先遍历(队列实现)
// 广度优先遍历
public static void bfs(TreeNode root){
LinkedList<TreeNode> list = new LinkedList<>();
list.add(root);
while (list != null && list.size() > 0){
TreeNode node = list.removeFirst();
System.out.println(node.value);
if (node.left != null){
list.add(node.left);
}
if (node.right != null){
list.add(node.right);
}
}
}
先序遍历的非递归实现,基本都是用栈
先序遍历(栈实现)
// 先序遍历
public static void dfs(TreeNode root){
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (stack != null && stack.size() > 0){
TreeNode node = stack.pop();
System.out.println(node.value);
if (node.right != null){
stack.push(node.right);
}
if (node.left != null){
stack.push(node.left);
}
}
}
先序遍历(递归实现)
public static void rootFirst(TreeNode root) {
if (root == null) {
return;
}
System.out.println(root.value);
rootFirst(root.left);
rootFirst(root.right);
}
中序遍历(栈实现)
先向栈压入所有左节点,然后根据条件弹出。当弹出的节点有right节点时,压入这个right节点。
public static void rootMid(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.isEmpty()) {
while (stack.peek().left != null) {
stack.push(stack.peek().left);
}
while (!stack.isEmpty()) {
TreeNode pop = stack.pop();
System.out.println(pop.value);
if (pop.right != null) {
stack.push(pop.right);
break;
}
}
}
}
中序遍历(递归实现)
public static void rootLast(TreeNode root) {
if (root == null) {
return;
}
rootFirst(root.left);
System.out.println(root.value);
rootFirst(root.right);
}
后序遍历(栈实现)
后续遍历结果的 倒序。 类似于先序遍历的镜像。基于先序遍历的栈实现。
压栈时,按照:左、右 压入。 出栈时即可得到:右,左 的顺序。
为了得到镜像,使用队列将其反过来输出即可。
public static void rootLast(TreeNode root) {
Stack<TreeNode> stack = new Stack<>();
LinkedList<Integer> result = new LinkedList<>();
stack.push(root);
while (stack != null && stack.size() > 0) {
TreeNode node = stack.pop();
result.addFirst(node.value);
if (node.left != null) {
stack.push(node.left);
}
if (node.right != null) {
stack.push(node.right);
}
}
System.out.println(result);
}
后序遍历(递归)
public static void rootLast(TreeNode root) {
if (root == null) {
return;
}
rootLast(root.left);
rootLast(root.right);
System.out.println(root.value);
}