105. Construct Binary Tree from Preorder and Inorder Traversal

Given preorder and inorder traversal of a tree, construct the binary tree.

Note:

You may assume that duplicates do not exist in the tree.

這道題目意思很明確:給出一棵樹的先序和中序遍歷(用數組形式給出),讓我們構造這棵樹。

我們知道,先序遍歷是根左右的順序,所以先序遍歷數組的第一個元素是樹的根,而中序遍歷是左根右的順序,所以可以通過先序遍歷找到樹的根,再根據中序遍歷去找樹的左右子樹,然後用遞歸的方法去找左右子樹的根和其左右子樹,直到搜索完畢爲止。

這裏用pre_start表示preorder的開始索引,用in_start表示inorder的開始索引,in_end表示inorder的結束索引,當找到樹的根在inorder中的索引index之後之後,左子樹的pre_start變成pre_start+1(因爲preorder的pre_start+1表示左子樹的根),並且左子樹在inorder中的開始和結束索引變爲in_start和index-1,右子樹的pre_start變爲pre_start+index-instart+1,因爲右子樹在pre_order中的根索引計算方式爲:pre_start再加上左子樹的所有節點個數(index-1-in_start+1=index-in_start)再加上1,在inorder中的開始和結束索引分別爲index+1和in_end,因爲每次遍歷的節點都用TreeNode root保存,所以最後返回root即可,代碼如下:

public class BuildTree {
	public class TreeNode {
	      int val;
	      TreeNode left;
	      TreeNode right;
	      TreeNode(int x) { val = x; }
	  }
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return help(0,0,inorder.length-1,preorder,inorder);
    }
    public TreeNode help(int pre_start,int in_start,int in_end,int[] preorder, int[] inorder){
    	if(pre_start>preorder.length-1||in_start>in_end){
    		return null;
    	}
    	TreeNode root = new TreeNode(preorder[pre_start]);
    	int index = 0;
    	for(int i=in_start;i<=in_end;i++){
    		if(inorder[i]==root.val){
    			index = i;
    		}
    	}
    	root.left = help(pre_start+1,in_start,index-1,preorder,inorder);
    	root.right = help(pre_start+index-in_start+1,index+1,in_end,preorder,inorder);
    	return 	root;
    }
}


發佈了64 篇原創文章 · 獲贊 9 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章