[劍指offer] --5.重建二叉樹
阿新 • • 發佈:2018-11-01
題目描述
輸入某二叉樹的前序遍歷和中序遍歷的結果,請重建出該二叉樹。假設輸入的前序遍歷和中序遍歷的結果中都不含重複的數字。例如輸入前序遍歷序列{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6},則重建二叉樹並返回。
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { } }
思路
public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { TreeNode root=reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1); return root; } //前序遍歷{1,2,4,7,3,5,6,8}和中序遍歷序列{4,7,2,1,5,3,8,6} private TreeNode reConstructBinaryTree(int [] pre,int startPre,int endPre,int [] in,int startIn,int endIn) { //判定條件,越界即左右子節點不存在 if(startPre>endPre||startIn>endIn) { return null; } TreeNode root=new TreeNode(pre[startPre]); for(int i=startIn;i<=endIn;i++) { if(in[i]==pre[startPre]){ //startpre+1,指的是前序遍歷左子樹的開始位置,即前序遍歷根節點的下一個節點。 //i-startin,i指的是中序遍歷根節點的位置,減去中序遍歷開始位置即左子樹的長度。 //所以i-startiin+starpre是前序遍歷左子樹結束的位置。 //根據中序遍歷+前序遍歷的特點,pre[starpre+1]就是當前節點的左子節點,pre[i-starin+starpre+1]就是當前節點的右子節點; root.left=reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); root.right=reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); break; } } return root; } static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } }