zoukankan      html  css  js  c++  java
  • 106. Construct Binary Tree from Inorder and Postorder Traversal

    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;
        }
    }

  • 相关阅读:
    [BZOJ4034][HAOI2015]树上操作
    [BZOJ1030][JSOI2007]文本生成器
    [BZOJ2763][JLOI2011]飞行路线
    [POJ3667]Hotel
    [codevs1566]染色
    [codevs2460]树的统计
    [BZOJ2667][cqoi2012][kcoj]模拟工厂
    [NOI2009][codevs1846]KCOJ0191]植物大战僵尸
    [POJ1087]A Plug for UNIX
    Educational Round 66 题解
  • 原文地址:https://www.cnblogs.com/wentiliangkaihua/p/11441287.html
Copyright © 2011-2022 走看看