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.

    题目:给定一个树的中序排列和后续排列数组,重新绘制出该树

    思路:由于后序的顺序的最后一个肯定是根,所以原二叉树的根节点可以知道,题目中给了一个很关键的条件就是树中没有相同元素,有了这个条件我们就可以在中序遍历中也定位出根节点的位置,并以根节点的位置将中序遍历拆分为左右两个部分,分别对其递归调用原函数。

     1     
     2     private int getIndexInInorder(int[] inorder, int val) {
     3         for (int i = 0; i < inorder.length; i++)  if (val == inorder[i]) return i;
     4         return -1;
     5     }
     6     
     7     private TreeNode buildPostAndIn(int[] postorder, int[] inorder, int postIndex,
     8                                     int startInIndex, int endInIndex) {
     9         if (endInIndex < startInIndex) return null;
    10         TreeNode node = new TreeNode(postorder[postIndex]);//后续,最后一个节点一定是根节点
    11         int index = getIndexInInorder(inorder,node.val); //获取该节点在中序数组中的位置,进一步结合startInIndex和endInIndex可以获得左右字树的范围
    12         int lenL = index - startInIndex;
    13         int lenR = endInIndex - index;
    14         if (lenL > 0) node.left = buildPostAndIn(postorder, inorder, postIndex - lenR - 1, startInIndex,
    15                 index - 1);
    16         if (lenR > 0) node.right = buildPostAndIn(postorder, inorder, postIndex - 1,
    17                 index + 1, endInIndex);
    18         return node;
    19     }
    20     
    21     public TreeNode buildTree(int[] inorder, int[] postorder) {
    22         if (postorder == null || postorder.length == 0) return null;
    23         if (inorder == null || inorder.length == 0) return null;
    24         if (postorder.length != inorder.length) return null;
    25         return buildPostAndIn(postorder, inorder, postorder.length-1, 0, inorder.length - 1);        
    26     }
  • 相关阅读:
    Linux命令应用大词典-第11章 Shell编程
    Kubernetes 学习12 kubernetes 存储卷
    linux dd命令
    Kubernetes 学习11 kubernetes ingress及ingress controller
    Kubernetes 学习10 Service资源
    Kubernetes 学习9 Pod控制器
    Kubernetes 学习8 Pod控制器
    Kubernetes 学习7 Pod控制器应用进阶2
    Kubernetes 学习6 Pod控制器应用进阶
    Kubernetes 学习5 kubernetes资源清单定义入门
  • 原文地址:https://www.cnblogs.com/wzj4858/p/7677241.html
Copyright © 2011-2022 走看看