zoukankan      html  css  js  c++  java
  • 剑指Offer07.重建二叉树

    题目链接:重建二叉树
    思路:根据前序和中序的排列规律,在中序遍历时,根节点的左边是左子树结点,右边是右子树结点,而前序遍历中首先出现根结点,紧接着根结点的是左子树结点,然后是右子树结点。所以,我们只需要确定在前序和中序中根结点的位置,通过根结点可以知道左子树和右子树结点的位置,该问题便转化为根据左右子树前序和中序遍历构造树,这是一个递归的过程。
    代码:

    /**
     * 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) {
            return helper(preorder, inorder, 0, preorder.length-1, 0, inorder.length-1);
        }
    
        private TreeNode helper(int[] preorder ,int[] inorder, int pstart, int pend, int istart, int iend){
            if(pstart > pend || istart > iend) return null;
            TreeNode root = new TreeNode(preorder[pstart]);
            int tidx = istart;
            while(root.val != inorder[tidx]) tidx++;
    
            root.left = helper(preorder, inorder, pstart+1, pstart + tidx - istart, istart, tidx-1);
            root.right = helper(preorder, inorder, pstart + tidx - istart + 1, pend, tidx+1, iend);
            return root;
        }
    }
    
  • 相关阅读:
    Arduino-原理图标识
    python-垃圾回收机制
    利用浮力测密度
    sys模块-与python解释器交互的模块
    第十一章第二节 功率
    第十一章第一节 功
    类-描述器-把类对象方法转变为属性方式
    H5浏览器播放RTMP直播流
    如何查看某个端口被谁占用
    OBS第三方推流直播教程
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14192618.html
Copyright © 2011-2022 走看看