• 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;
        }
    }
  • 相关阅读:
    python 04 list增删改查 迷途小书童
    xhtml+css符合标准的WEB设计
    在Ubuntu16.0.4安装hipcaffe
    简单使用OpenSSL生成密钥
    Ubuntu 16.04 集成安装Apache+PHP+Kerberos+LDAP+phpLDAPadmin
    Ubuntu 安装mysql & 自定义数据存储目录
    TestLink+Jenkins在Ubuntu16.04搭建集成测试环境
    Rancher 2.1平台搭建及使用
    JavaFX_homework1_pane
    linux 命令1 转
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3545285.html
Copyright © 2020-2023  润新知