zoukankan      html  css  js  c++  java
  • Construct Binary Tree from Inorder and Postorder Traversal——LeetCode

    Given inorder and postorder traversal of a tree, construct the binary tree.

    题目大意:给定一个二叉树的中序和后续序列,构建出这个二叉树。

    解题思路:首先后序序列的最后一个是根节点,然后在中序序列中找到这个节点,中序序列中这个节点左边的是根节点的左子树,右边的是右子树,由此递归构建出完整的树。

    Talk is cheap:

        public TreeNode buildTree(int[] inorder, int[] postorder) {
            if (inorder == null || postorder == null) {
                return null;
            }
            int inLen = inorder.length;
            int postLen = postorder.length;
            if ((inLen == 0 && postLen == 0) || inLen != postLen) {
                return null;
            }
    
            TreeNode root = new TreeNode(postorder[postLen - 1]);
            if (inLen == 1) {
                return root;
            }
            int pos = 0;
            for (int i = 0; i < inLen; i++) {
                if (inorder[i] == postorder[postLen - 1]) {
                    pos = i;
                    break;
                }
            }
            int[] inLeft = Arrays.copyOfRange(inorder, 0, pos);
            int[] inRight = Arrays.copyOfRange(inorder, pos + 1, inLen);
            int[] postLeft = Arrays.copyOfRange(postorder, 0, pos);
            int[] postRight = Arrays.copyOfRange(postorder, pos, postLen - 1);
    
            root.left = buildTree(inLeft, postLeft);
            root.right = buildTree(inRight, postRight);
            return root;
        }
  • 相关阅读:
    vector的erase函数
    结构体定义容易混淆的地方
    JavaScript重点知识
    JS中预解析案例分析
    浏览器console控制台不显示编译错误/警告
    强烈推荐一款强大的公式编辑器软件AxMath
    DIV+CSS布局
    CSS-常见属性
    CSS-定义样式表
    CSS-使用CSS样式的方式
  • 原文地址:https://www.cnblogs.com/aboutblank/p/4444469.html
Copyright © 2011-2022 走看看