码迷,mamicode.com
首页 > 其他好文 > 详细

Construct Binary Tree from Preorder and Inorder Traversal

时间:2018-08-28 21:13:50      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:cti   ||   base   dtree   ini   ons   class   uil   res   

Construct Binary Tree from Preorder and Inorder Traversal


/**
 * 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) {
        if(preorder == null || inorder == null || preorder.length == 0 || 
          inorder.length == 0 || preorder.length != inorder.length){
            return null;
        }
        return construct(preorder, inorder, 0, 0, inorder.length - 1);
    }
    private TreeNode construct(int[] preorder, int[] inorder, int preStart, 
                              int inStart, int inEnd){
        // BASE CASE 
        if(preStart > preorder.length || inStart > inEnd) return null;
        
        
        // recursion + induction rule 
        // find the size of left subtree 
        int i = inStart;
        while (i <= inEnd){
            if(inorder[i] == preorder[preStart]){
                break;
            }
            i++;
        }
        // root 
        TreeNode root = new TreeNode(preorder[preStart]);
        root.left = construct(preorder, inorder, preStart + 1, inStart, i -1);
        root.right = construct(preorder, inorder, preStart + (i - inStart + 1), i + 1, inEnd);
        return root;
    }
}

 

Construct Binary Tree from Preorder and Inorder Traversal

标签:cti   ||   base   dtree   ini   ons   class   uil   res   

原文地址:https://www.cnblogs.com/tobeabetterpig/p/9550674.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!