zoukankan      html  css  js  c++  java
  • 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.

    class TreeNode {
         int val;
         TreeNode left;
         TreeNode right;
         TreeNode(int x) { val = x; }
    }
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if(inorder==null||postorder==null||inorder.length==0||postorder.length!=postorder.length){
                return null;
            }
            return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1);
        }
    
        private TreeNode buildTree(int[] inorder, int instar, int inend,int[] postorder, int poststar, int postend) {
            if(instar>inend||poststar>postend)return null;
            int value=postorder[postend];
            TreeNode root=new TreeNode(value);
            int index;
            for (index =instar; index < inend&&inorder[index]!=value; index++){
                
            }
            root.left=buildTree(inorder,instar,index-1,postorder,poststar,poststar+index-instar-1);
            root.right=buildTree(inorder,index+1,inend,postorder,poststar+index-instar,postend-1);
            return root;
        }
    }
  • 相关阅读:
    集合容器
    洛谷P3953 逛公园
    洛谷P1967 货车运输
    洛谷P1073 最优贸易
    洛谷P4568 [JLOI2011]飞行路线
    洛谷P1265 公路修建
    洛谷P1503 鬼子进村
    洛谷P1613 跑路
    洛谷P4933 大师
    洛谷P4017 最大食物链计数
  • 原文地址:https://www.cnblogs.com/softwarewebdesign/p/5518704.html
Copyright © 2011-2022 走看看