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;
        }
    }
  • 相关阅读:
    进程和线程
    进程通信、同步与调度
    文件和文件系统
    【nexys3】【verilog】小设计——拆弹游戏
    Qt4开发环境搭建(Qt4.8.7+mingw4.8.2+Qt Creator4.2.0)
    GPL和LGPL
    【rpi】使用putty远程连接rpi(ssh)
    mysql 命令 小结
    安装mysql zip 安装包 Navicat连接
    python虚拟环境 virtualenv工具
  • 原文地址:https://www.cnblogs.com/RazerLu/p/3545285.html
Copyright © 2011-2022 走看看