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

106. Construct Binary Tree from Inorder and Postorder Traversal - Medium

时间:2019-01-01 11:14:07      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:efi   class   note   order   style   ons   tar   binary   start   

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

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

For example, given

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

Return the following binary tree:

    3
   /   9  20
    /     15   7

 

time: O(nlogn) ~ O(n^2), space: O(height)

/**
 * 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[] inorder, int[] postorder) {
        if(inorder == null || postorder == null || inorder.length == 0 || inorder.length != postorder.length) {
            return null;
        }
        return buildTree(postorder, postorder.length - 1, inorder, 0, inorder.length - 1);
    }
    
    public TreeNode buildTree(int[] postorder, int post_start, int[] inorder, int in_start, int in_end) {
        if(post_start < 0 || in_start > in_end) {
            return null;
        }
        TreeNode root = new TreeNode(postorder[post_start]);
        int idx = 0;
        for(int i = in_start; i <= in_end; i++) {
            if(inorder[i] == postorder[post_start]) {
                idx = i;
                break;
            }
        }

        root.left = buildTree(postorder, post_start - (in_end - idx + 1), inorder, in_start, idx - 1);
        root.right = buildTree(postorder, post_start - 1, inorder, idx + 1, in_end);
        
        return root;
    }
}

 

106. Construct Binary Tree from Inorder and Postorder Traversal - Medium

标签:efi   class   note   order   style   ons   tar   binary   start   

原文地址:https://www.cnblogs.com/fatttcat/p/10204151.html

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