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.

    后续遍历 根节点在最后一个元素

    /**
     * Definition for binary tree
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if (postorder == null || inorder == null) {
                return null;
            }
            int postLen = postorder.length;
            int inLen = inorder.length;
            if (postLen == 0 || inLen == 0) {
                return null;
            }
    
            return constructTree(postorder, 0, postLen - 1, inorder, 0, inLen - 1);
        }
        
        public static TreeNode constructTree(int[] postorder, int postStart, int postEnd,
                int[] inorder, int inStart, int inEnd) {
            int rootVal = postorder[postEnd];
            TreeNode root = new TreeNode(rootVal);
            root.left = null;
            root.right = null;
            
            if(postStart == postEnd && postorder[postStart] == inorder[inStart]){
                return root;
            }
            
            int i = inStart;
            for(; i <= inEnd; i++){
                if(inorder[i] == rootVal){
                    break;
                }
            }
            int leftLen = i - inStart;
            // 如果左子树不为空
            if(leftLen > 0){
                root.left = constructTree(postorder, postStart, postStart + leftLen - 1,
                        inorder, inStart, i - 1);
            }
            // 如果右子树不为空
            if(inEnd > i){
                root.right = constructTree(postorder, postStart + leftLen, postEnd - 1,
                        inorder, i + 1, inEnd);
            }
            return root;
        }
    }
  • 相关阅读:
    头文件stdio与stdlib.h的区别
    宝塔利用git+ webhooks 实现git更新远程同步Linux服务器
    Linux源码安装步骤
    Promise.all和Promise.race区别,和使用场景
    vue显示富文本
    Js实现将html页面或div生成图片
    JS
    关于Swiper和vue数据顺序加载问题处理
    php 数据库备份(可用作定时任务)
    js async await 终极异步解决方案
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3545285.html
Copyright © 2011-2022 走看看