• 106.Construct Binary Tree from Inorder and Postorder Traversal


    题目链接

    题目大意:根据中序和后序构建二叉树。

    法一:与105类似,只是这里是根据后序来确定根节点。代码如下(耗时15ms):

     1     public TreeNode buildTree(int[] inorder, int[] postorder) {
     2         if(postorder.length == 0 || inorder.length == 0) {
     3             return null;
     4         }
     5         return dfs(inorder, postorder, 0, inorder.length - 1, 0, postorder.length - 1);
     6     }
     7     private TreeNode dfs(int[] inorder, int[] postorder, int inL, int inR, int postL, int postR) {
     8         TreeNode root = new TreeNode(postorder[postR]);
     9         int rootIndex = inL;
    10         while(inorder[rootIndex] != postorder[postR]) {
    11             rootIndex++;
    12         }
    13         int leftLen = rootIndex - inL;
    14         int rightLen = inR - rootIndex;
    15         if(leftLen != 0) {
    16             root.left = dfs(inorder, postorder, inL, rootIndex - 1, postL, postL + leftLen - 1);
    17         }
    18         else {
    19             root.left = null;
    20         }
    21         if(rightLen != 0) {
    22             root.right = dfs(inorder, postorder, rootIndex + 1, inR, postL + leftLen, postR - 1);
    23         }
    24         else {
    25             root.right = null;
    26         }
    27         return root;
    28     }
    View Code
  • 相关阅读:
    Oracle EXTRACT()函数与to_char() 函数
    Java内部类
    SQL 之 Group By
    Android LayoutInflater布局填充器
    JS 图片转Base64
    C# 事件与委托的区别
    AngularJS的循环输出
    jquery实现button倒计时
    重新理解B/S和C/S的区别
    HashMap与HashTable
  • 原文地址:https://www.cnblogs.com/cing/p/9020261.html
Copyright © 2020-2023  润新知