zoukankan      html  css  js  c++  java
  • 根据前序遍历和中序遍历创建出二叉树

    二叉树

    class Solution {
        public static void main(String[] args) {
    
        }
    
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if (preorder == null || preorder.length == 0) {
                return null;
            }
            int begin = 0;
            int start = 0;
            int end = preorder.length - 1;
            return buildTree2(preorder, inorder, begin, start, end);
    
        }
    
        public TreeNode buildTree2(int[] preorder, int[] inorder, int begin, int start, int end) {
            if (start > end) {
                return null;
            }
            int root = preorder[begin];
            TreeNode node = new TreeNode(root);
            int k = search(inorder, start, end, root);
            node.left = buildTree2(preorder, inorder, begin + 1, start, k - 1);
            node.right = buildTree2(preorder, inorder, begin + k - start + 1, k + 1, end);
            return node;
    
        }
    
        public int search(int[] inorder, int start, int end, int obj) {
            for (int i = start; i <= end; ++i) {
                if (obj == inorder[i]) {
                    return i;
                }
            }
            return 0;
        }
    
        class TreeNode {
            int val;
            TreeNode left;
            TreeNode right;
    
            TreeNode(int x) {
                val = x;
            }
        }
    
    }
  • 相关阅读:
    131.著作权
    130.专利权
    idea新用法
    map的put和putIfAbsent使用
    netty的option和childOption
    Java8 lam。。。表达式
    protobuf学习
    protobuf生成
    idea调试
    spring,mapper的参数
  • 原文地址:https://www.cnblogs.com/erdanyang/p/12940679.html
Copyright © 2011-2022 走看看