详见jiyangg.github.io(二叉树集锦)html
二叉树节点:node
class BinaryTreeNode { int val; BinaryTreeNode left; BinaryTreeNode right; public BinaryTreeNode(int val) { this.val = val; } }
void visit(BinaryTreeNode node) { System.out.print(node.val + " "); }
int TreeNodeCount(BinaryTreeNode root) { if (root == null) { return 0; } return TreeNodeCount(root.left) + TreeNodeCount(root.right) + 1; }
int TreeDepth(BinaryTreeNode root) { if (root == null) { return 0; } int leftDepth = TreeDepth(root.left); int rightDepth = TreeDepth(root.right); return leftDepth > rightDepth ? (leftDepth + 1) : (rightDepth + 1); }
void preOrderTraverse(BinaryTreeNode root) { if (root == null) { return; } visit(root); //访问根节点 preOrderTraverse(root.left); //前序遍历左子树 preOrderTraverse(root.right); //前序遍历右子树 }
void inOrderTraverse(BinaryTreeNode root) { if (root == null) { return; } inOrderTraverse(root.left); //中序遍历左子树 visit(root); //访问根节点 inOrderTraverse(root.right); //中序遍历右子树 }
void postOrderTraverse(BinaryTreeNode root) { if (root == null) { return; } postOrderTraverse(root.left); //后序遍历左子树 postOrderTraverse(root.right); //后序遍历右子树 visit(root); //访问根节点 }
void levelTraverse(BinaryTreeNode root){ if (root == null) { return; } Queue<BinaryTreeNode> queue = new ArrayDeque<>(); queue.add(root); while (!queue.isEmpty()) { BinaryTreeNode node = queue.poll(); visit(node); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } }
根据前序遍历和中序遍历的结果重建二叉树git
经过前序遍历的第一个元素为树的根找到根节点,而后在中序遍历中找到根节点的位置就能肯定树的左右子树的节点数。github
BinaryTreeNode reConstructBinaryTree(int[] pre, int[] in) { if (pre == null || in == null || pre.length <= 0 || in.length <= 0) { return null; } //储存根节点 BinaryTreeNode root = new BinaryTreeNode(pre[0]); int rootPositionInOrder = -1; //查找根节点在中序遍历的位置 for (int i = 0; i < in.length; i++) { if (root.val == in[i]) { rootPositionInOrder = i; break; } } if (rootPositionInOrder == -1) { return null; } //肯定左子树节点数 int numOfLeft = rootPositionInOrder; //存储左子树前序遍历结果 int[] leftPre = new int[numOfLeft]; for (int i = 0; i < numOfLeft; i++) { leftPre[i] = pre[i + 1]; } //储存左子树中序遍历结果 int[] leftIn = new int[numOfLeft]; for (int i = 0; i < numOfLeft; i++) { leftIn[i] = in[i]; } //重建左子树 root.left = reConstructBinaryTree(leftPre, leftIn); //肯定右子树节点数 int numOfRight = in.length - numOfLeft - 1; //储存右子树前序遍历结果 int[] rightPre = new int[numOfRight]; for (int i = 0; i < numOfRight; i++) { rightPre[i] = pre[i + numOfLeft + 1]; } //储存右子树中序遍历结果 int[] rightIn = new int[numOfRight]; for (int i = 0; i < numOfRight; i++) { rightIn[i] = in[i + numOfLeft + 1]; } //重建右子树 root.right = reConstructBinaryTree(rightPre, rightIn); return root; }