1. 二叉树结构
2. 二叉树节点遍历顺序
前序:
每颗子树以 中 —》左 —》右 遍历
A B D E H C F G
中序:
每颗子树以 左 —》中 —》右 遍历
D B E H A F C G
后序:
每颗子树以 左 —》右 —》中 遍历
D H E B F G C A
代码实现:
public class BinaryTree {
static class TreeNode {
public TreeNode left;
public char val;
public TreeNode right;
public TreeNode(char val) {
this.val = val;
}
}
public TreeNode createTree() {
TreeNode A = new TreeNode('A');
TreeNode B = new TreeNode('B');
TreeNode C = new TreeNode('C');
TreeNode D = new TreeNode('D');
TreeNode E = new TreeNode('E');
TreeNode F = new TreeNode('F');
TreeNode G = new TreeNode('G');
TreeNode H = new TreeNode('H');
A.left = B;
B.left = D;
B.right = E;
E.right = H;
A.right = C;
C.left = F;
C.right = G;
return A;
}
// 前序 - 根左右
public void preOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
preOrder(root.left);
preOrder(root.right);
}
// 中序
public void inOrder(TreeNode root) {
if (root == null) {
return;
}
inOrder(root.left);
System.out.print(root.val + " ");
inOrder(root.right);
}
// 后序
public void postOrder(TreeNode root) {
if (root == null) {
return;
}
postOrder(root.left);
postOrder(root.right);
System.out.print(root.val + " ");
}
public static void main(String[] args) {
BinaryTree binaryTree = new BinaryTree();
TreeNode root = binaryTree.createTree();
binaryTree.preOrder(root);
System.out.println();
binaryTree.inOrder(root);
System.out.println();
binaryTree.postOrder(root);
}
}
3. 递归序理解二叉树遍历
除了空节点外 每一个节点一定会到达3次
第一次到达访问节点: 前序,第二次到达访问节点: 中序,第三次到达访问节点: 后序
访问节点的时机不同 遍历顺序也就不同
以递归序为例:
标签:遍历,TreeNode,前中,right,二叉树,new,root,public From: https://www.cnblogs.com/xumu7/p/17969802