重建二叉樹以及四種遍歷
重建二叉樹(劍指offer第7題)
根據前序+中序或者後序+中序遍歷可以唯一確定一棵二叉樹。
三種遍歷方式(以根分類)
- 前序遍歷:先訪問根節點,再訪問左子節點,最後訪問右子節點。
- 中序遍歷:先訪問左子節點,再訪問根節點,最後訪問右子節點。
- 後續遍歷:先訪問左子節點,再訪問右子節點,最後訪問根節點。
層序遍歷
一層一層的遍歷,使用的是Queue,可以得到樹的最大寬度。
代碼實現
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Solution {
public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
if(pre.length == 0 || pre.length != in.length){
return null;
}
TreeNode root = new TreeNode(pre[0]);
for(int i = 0; i < pre.length; i++){
if(pre[0] == in[i]){
root.left = reConstructBinaryTree(Arrays.copyOfRange(pre, 1, 1 + i),Arrays.copyOfRange(in, 0, i));
root.right = reConstructBinaryTree(Arrays.copyOfRange(pre, 1 + i, pre.length), Arrays.copyOfRange(in, 1 + i, pre.length));
break;
}
}
return root;
}
static List<Integer> list = new ArrayList<Integer>();//中序遍歷
public static List<Integer> inOrderTraversal(TreeNode root){
if(root != null){
if(root.left != null){
inOrderTraversal(root.left);
}
list.add(root.val);
if(root.right != null){
inOrderTraversal(root.right);
}
}
return list;
}
static List<Integer> list2 = new ArrayList<Integer>();//前序遍歷
public static List<Integer> preOrderTraversal(TreeNode root){
list2.add(root.val);
if(root.left != null){
preOrderTraversal(root.left);
}
if(root.right != null){
preOrderTraversal(root.right);
}
return list2;
}
static List<Integer> list3 = new ArrayList<Integer>();//後序遍歷
public static List<Integer> postTraversal(TreeNode root){
if(root.left != null){
postTraversal(root.left);
}
if(root.right != null){
postTraversal(root.right);
}
list3.add(root.val);
return list3;
}
public static void main(String[] args) {
int[] pre = {1,2,4,7,3,5,6,8};
int[] in = {4,7,2,1,5,3,8,6};
TreeNode root = reConstructBinaryTree(pre,in);
System.out.println(root);
System.out.println("in=" + inOrderTraversal(root));
System.out.println("pre=" + preOrderTraversal(root));
System.out.println("post=" + postTraversal(root));
}
}
static List<Integer> list4 = new ArrayList<Integer>();//層序遍歷
public static List<Integer> levelOrder(TreeNode root){
int count = 0;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
count = 1;
int a = 0;
while (queue.size() > 0){
TreeNode tn = queue.poll();
count--;
list4.add(tn.val);
if(tn.left != null){
queue.add(tn.left);
}
if( tn.right != null){
queue.add(tn.right);
}
if(count == 0){
count = queue.size();
}
if(a < count){
a = count;
}
}
System.out.println(a);
return list4;
}