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;
        }
    }
    
  • 相关阅读:
    static、final、this、super关键
    细节二:参数、引用类型、实例化
    枚举类型
    单例模式
    细节一:字符串、switch、默认值、数组
    类属性和类方法
    装饰器模式
    TreeSet
    可见参数和增强for以及自动拆装箱
    静态导入
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14192618.html
Copyright © 2011-2022 走看看