zoukankan      html  css  js  c++  java
  • 105 从前序与中序遍历序列构造二叉树

    /*
     * @lc app=leetcode.cn id=105 lang=java
     *
     * [105] 从前序与中序遍历序列构造二叉树
     */
    
    // @lc code=start
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            if(preorder== null || preorder.length <= 0){
                return null;
            }
    
            int preL = 0, preR = preorder.length - 1;
            int inL = 0, inR = inorder.length - 1;
            return helper(preorder, preL, preR, inorder, inL, inR);
        }
    
        public TreeNode helper(int[] preorder, int preL, int preR, int[] inorder, int inL, int inR){
            if(preL > preR || inL > inR || preR > preorder.length || inR > inorder.length){
                return null;
            }
            int rootIndex = 0;
            TreeNode root = new TreeNode(preorder[preL]);
            for(int i = inL; i <= inR; i++){
                if(inorder[i] == root.val){
                    rootIndex = i;
                    break;
                }
            }
    
            root.left = helper(preorder, preL + 1, preL + (rootIndex - inL), inorder, inL, rootIndex - 1);
            root.right = helper(preorder, preL + (rootIndex - inL) + 1, preR, inorder, rootIndex + 1, inR);
    
            return root;
        }
    }
    // @lc code=end
    
    
    
  • 相关阅读:
    软件工程导论P53,习题2.4
    视图和数据表的区别
    无法从“object”转换为“string”
    Oracle 密码重置
    Struts2 上传下载
    Spring 事务管理
    JSP 指令和动作
    JS 禁用回车、后退事件、form 表单不可编辑
    关于 in 和 exist 的理解
    Oracle clob 操作函数
  • 原文地址:https://www.cnblogs.com/realzhaijiayu/p/13557302.html
Copyright © 2011-2022 走看看