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

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

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

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
     //从中序与后序遍历构建树,思想与上一题一样
     //唯一区别是后序遍历的尾为root,而先序遍历的首为root
     public class Solution {
         public int findRoot(int[] inorder, int key){     //在中序遍历中定位root
             if(inorder.length==0) return -1;
             int index = -1;
             for(int i=0; i<inorder.length; i++){
                 if(inorder[i]==key){
                     index = i; break;
                 }
             }
             return index;
         }
         
         //通过递归实现构建树的主逻辑
         public TreeNode buildTree(int[] inorder, int[] postorder, int instart, int inend, int postart, int poend){
             if(inorder.length==0 || postorder.length==0) return null;
             if(instart > inend) return null;
             TreeNode root = new TreeNode(postorder[poend]);
             int index = findRoot(inorder, root.val);
             root.left = buildTree(inorder, postorder, instart, index-1, postart, postart+index-1-instart);
             root.right = buildTree(inorder, postorder, index+1, inend, postart+index-1-instart+1, poend-1);
             return root;
         }
         
         //****leetcode主函数****
         public TreeNode buildTree(int[] inorder, int[] postorder) {
             return buildTree(inorder, postorder, 0, inorder.length-1, 0, postorder.length-1);
         }
     }
    



  • 相关阅读:
    Opportunities
    去考試6/16
    WP数据绑定 GIS
    wp 之path详细 以及一个关于LinearGradientBrush 的动画 GIS
    windows phone 多触控画图并保存到 手机图片库 GIS
    windwos phone 的多任务 GIS
    导航基础 GIS
    Windows Phone 7 页面旋转动画 GIS
    一个小范围 滑动的动画 GIS
    wp 的手势Gestures: flick, pan, and stretch GIS
  • 原文地址:https://www.cnblogs.com/dosmile/p/6444464.html
Copyright © 2011-2022 走看看