• LeetCode 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.


    题目标签:Array, Tree

      这到题目和105 几乎是一摸一样的,唯一的区别就是把pre-order 换成 post-order。因为post-order是最后一个数字是root,所以要从右向左的遍历。还需要把helper function 里的 right child 和 left child 顺序更换一下,并且要把相关的代入值也改一下。具体可以看code。

    Java Solution:

    Runtime beats 68.55% 

    完成日期:08/26/2017

    关键词:Array, Tree

    关键点:递归;利用post-order 和 in-order 的位置关系递归

     1 /**
     2  * Definition for a binary tree node.
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 class Solution 
    11 {
    12     public TreeNode buildTree(int[] inorder, int[] postorder) 
    13     {
    14         Map<Integer, Integer> inMap = new HashMap<Integer, Integer>();
    15         
    16         // save inorder number as key, position as value into map
    17         for(int i=0; i<inorder.length; i++)
    18             inMap.put(inorder[i], i);
    19         
    20         
    21         TreeNode root = helper(postorder, postorder.length-1, 0, inorder.length - 1, inMap);
    22         
    23         return root;    
    24     }
    25     
    26     public TreeNode helper(int[] postorder, int postEnd, int inStart, int inEnd, 
    27             Map<Integer, Integer> inMap)
    28     {
    29         if(inStart > inEnd)
    30             return null;
    31         
    32         int rootVal = postorder[postEnd];
    33         TreeNode root = new TreeNode(rootVal);
    34         int inRoot = inMap.get(rootVal);  // position in inOrder
    35         
    36         /* inStart & inEnd: for left child, move inEnd to the left of root
    37          *                  for right child, move inStart to the right of root */
    38         root.right = helper(postorder, postEnd - 1, inRoot + 1, inEnd, inMap);
    39         /* postStart: for right left, go to inorder to check how many right children does root have,  
    40          * add it into postorder to skip them to reach left child */
    41         root.left = helper(postorder, postEnd - (inEnd - inRoot) - 1, inStart, inRoot - 1, inMap);
    42         
    43         return root;
    44     }
    45 }

    参考资料:N/A

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    说说毕业两年多的经历
    egret: if判断语句不能写在addEventListener监听事件外面吗?
    egret wing exml文件突然在设计和预览模式下不可见!
    egret:设置滚动视图、隐藏滚动条以及层级的问题
    egret:list网格布局
    egret 自动播放音乐问题:ios 自动播放音乐失效
    private static和public static的意义
    setTimeout()的第三个参数
    egret 学习之once()与addEventListener()
    egret 入门学习笔记之问题解决
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7439605.html
Copyright © 2020-2023  润新知