首页 > 其他 > 详细

106. Construct Binary Tree from Inorder and Postorder Traversal

时间:2019-09-01 09:39:32      阅读:75      评论:0      收藏:0      [点我收藏+]

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

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!