二叉树的前中后序遍历,合并,翻转操作
- 二叉树的遍历(traversing binary tree)是指从根结点出发,按照某种次序依次访问二叉树中所有的结点,使得每个结点被访问依次且仅被访问一次。
前序 | 中 | 左 | 右 |
中序 | 左 | 中 | 右 |
后序 | 左 | 右 | 中 |
java代码实现:
public class TwoTree { public static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public static void main(String args[]) { TreeNode root = new TreeNode(0); // 构建简单的二叉树 TreeNode node1 = new TreeNode(1); TreeNode node2 = new TreeNode(2); TreeNode node3 = new TreeNode(3); TreeNode node4 = new TreeNode(4); TreeNode node5 = new TreeNode(5); TreeNode node6 = new TreeNode(6); TreeNode node7 = new TreeNode(7); root.left = node1; root.right = node2; node1.left = node3; node1.right = node4; node2.left = node5; node2.right = node6; node4.right = node7; preOrderTravels(root); // 前序遍历一次 System.out.println(); middleOrderTravels(root); // 中序遍历一次 System.out.println(); lastOrderTravels(root); // 后序遍历一次 System.out.println(); root = invertBinaryTree(root); preOrderTravels(root); // 翻转后再前序遍历一次 root = mergeTrees(root, root); //合并两个树 System.out.println(); preOrderTravels(root); } // 前序遍历 public static void preOrderTravels(TreeNode node) { if (node == null) { return; } else { System.out.print(node.val + " "); preOrderTravels(node.left); preOrderTravels(node.right); } } // 中序遍历 public static void middleOrderTravels(TreeNode node) { if (node == null) { return; } else { middleOrderTravels(node.left); System.out.print(node.val + " "); middleOrderTravels(node.right); } } // 后序遍历 public static void lastOrderTravels(TreeNode node) { if (node == null) { return; } else { lastOrderTravels(node.left); lastOrderTravels(node.right); System.out.print(node.val + " "); } } // 翻转二叉树 private static TreeNode invertBinaryTree(TreeNode root) { if (root == null || (root.left == null && root.right == null)) return root;// 为空,或没有子树,直接返回 TreeNode tmp = root.right; // 右子树存入tmp中 root.right = invertBinaryTree(root.left);// 先处理左子树,然后接到root的右链接 root.left = invertBinaryTree(tmp); // 处理tmp中原来的右子树,然后接到root的左链接 return root; } // 合并两个二叉树 public static TreeNode mergeTrees(TreeNode t1, TreeNode t2) { TreeNode root = null; if (t1 == null && t2 == null) return root; if (t1 == null && t2 != null) { root = t2; } if (t1 != null && t2 == null) { root = t1; } if (t1 != null && t2 != null) { root = new TreeNode(t1.val + t2.val); root.left = mergeTrees(t1.left, t2.left); root.right = mergeTrees(t1.right, t2.right); } return root; } }