1. 程式人生 > >6.重建二叉樹(JAVA)

6.重建二叉樹(JAVA)

題目描述

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

具體實現

解題思路:利用遞迴來完成,重點是要利用好前序遍歷和中序遍歷的特點,兩者結合來完成遞迴,

  • 前序的起始值必然是根結點,然後去中序中找到這個根結點,這樣就能把左右子樹分開,接下來的重點就是在前序和中序中左右子樹邊界值的確定了。
  • 中序中比較簡單,因為根結點在中間分開了左右子樹;前序則需要利用中序的條件來確定,由中序左邊是左子樹得到左子樹個數,中序右邊是右子樹得到右子樹個數。
public class TreeNode {
	      int val;
	      TreeNode left;
	      TreeNode right;
	      TreeNode(int x) { val = x; }
	  }
	  public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
		  //呼叫遞迴
	        TreeNode root = reConstructBinaryTree(pre, 0, pre.length-1, in, 0, in.length-1);
	        return
root; } private TreeNode reConstructBinaryTree(int[] pre, int startPre, int endPre, int[] in, int startIn, int endIn) { //越界就返回null if(startPre > endPre || startIn > endIn) { return null; } //前序遍歷的起始點就是根結點 TreeNode root = new TreeNode(pre[startPre]); for(int i = 0
; i <= endIn; i++) { if(pre[startPre] == in[i]) {//根據前序遍歷得到的根結點在中序遍歷中查詢根結點的下標i //重點,裡面的起始值和結束值 //左子樹:前序遍歷中起始值為之前的起始值加一,終點值為前序起始值加上(中序的根值i-中序的起始值,即得到左子樹個數) // 中序遍歷中起始值為之前中序起始值,終點值為中序根結點減一即i-1 root.left = reConstructBinaryTree(pre,startPre+1,startPre+i-startIn,in,startIn,i-1); //右子樹:前序遍歷中起始值為前序起始值加上左子樹個數(i-startIn)再加1,終點值為前序的終點值。 // 中序遍歷中起始值為中序根結點加一(i+1),終點值為之前中序的終點值 root.right = reConstructBinaryTree(pre,i-startIn+startPre+1,endPre,in,i+1,endIn); break; } } return root; }