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

106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2019-09-01 10:42:11      阅读:87      评论:0      收藏:0      [点我收藏+]

标签:com   otv   note   and   src   ret   hat   nbsp   root   

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
/**
 * 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) {
        int length = inorder.length;
        return buildTree(inorder, 0, length - 1, postorder, 0, length - 1);
    }
    public TreeNode buildTree(int[] inorder, int instart, int inend, int[] postorder, int postart, int postend){
        if(instart > inend || postart > postend) return null;
        int rootval = postorder[postend];
        int rootind = 0;
        
        for(int i = instart; i <= inend; i++){
            if(rootval == inorder[i]){
                rootind = i;
                break;
            }
        }
        
        int len = rootind - instart;
        TreeNode root = new TreeNode(rootval);
        root.left = buildTree(inorder, instart, rootind-1, postorder, postart, postart + len - 1);
        root.right = buildTree(inorder, rootind + 1, inend, postorder, postart + len, postend-1 );
        return root;
    }
}

技术图片

 

106. Construct Binary Tree from Inorder and Postorder Traversal

标签:com   otv   note   and   src   ret   hat   nbsp   root   

原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11441287.html

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