劍指——重建二叉樹

重建二叉樹

輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。java


解題思路安全

根據前序遍歷的特色,第一個數就表明根節點。在中序遍歷序列中找到根節點,那麼根節點前的樹就是屬於左子樹的,後面的就是屬於右子樹的。spa

而後根據根節點在中序遍歷序列中的下標,肯定左子樹有多少個結點,右子樹有多少個結點,依據這個從前序遍歷序列中選取出左右子樹中的值。code

而後運用遞歸便可。blog

遞歸基本狀況:已經涵蓋在代碼中了,當兩個序列爲空時,就到了基本狀況。return null。遞歸


 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 import java.util.Arrays;
11 public class Solution {
12     public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
13         //遞歸基本條件
14         if(pre.length == 0 || in.length == 0)
15             return null;
16         //先肯定根節點
17         TreeNode root = new TreeNode(pre[0]);
18         //在中序遍歷序列中找到根節點
19         for(int i = 0; i < in.length; i ++){
20             if(in[i] == pre[0]){
21                 root.left = reConstructBinaryTree(
22                     Arrays.copyOfRange(pre, 1, i+1), Arrays.copyOfRange(in, 0, i)
23                 );
24                 root.right = reConstructBinaryTree(
25                     Arrays.copyOfRange(pre, i+1, pre.length), Arrays.copyOfRange(in, i+1, in.length)
26                 );
27                 break;//加不加好像差很少,不加感受安全一些,由於我想不清楚
28             }
29         }
30         return root;
31     }
32 }
相關文章
相關標籤/搜索