1. 程式人生 > >LeetCode刷題Medium篇Construct Binary Tree from Preorder and Inorder Traversal

LeetCode刷題Medium篇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.

For example, given

preorder = [3,9,20,15,7]
inorder = [9,3,15,20,7]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7

十分鐘嘗試

根據先序,中序遍歷結果構建二叉樹,沒有接觸過這類題目,學習一下思路吧。

根據先序遍歷,我們能夠知道根,比如先序遍歷的第一個元素是root元素。然後,找出當前根在中序遍歷中的位置,比如為index,那麼中序遍歷index左右側分別為左子樹和右子樹,遞迴呼叫,完成二叉樹的構建。

在遞迴呼叫的時候,左右子樹分割就是我們找到的inIndex,主要當前根節點索引的變化,左子樹是preStart+1,右子樹是preStart+inIndex-inStart+1

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return helper(0,0,inorder.length-1,preorder,inorder);
    }
    
    private TreeNode  helper(int preStart,int inStart,int inEnd,int[] preorder,int[] inorder){
        if(preStart>preorder.length-1||inStart>inEnd){
            return null;
        }
        //建立當前根,從先序遍歷獲取根節點
        int currRoot=preorder[preStart];
        TreeNode root=new TreeNode(currRoot);
        int inIndex=0;
        for(int i=0;i<inorder.length;i++){
            if(inorder[i]==currRoot){
                inIndex=i;
            }
        }
        //左子樹根節點為preStart+1,從先序遍歷獲得
        root.left=helper(preStart+1,inStart,inIndex-1,preorder,inorder);
        //右子樹根節點為preStart+inIndex-inStart+1,從先序遍歷獲得
        root.right=helper(preStart+inIndex-inStart+1,inIndex+1,inEnd,preorder,inorder);
        return root;
        
    }
}