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;
        }
    }
    
  • 相关阅读:
    2013总结,新的征程开始了!
    NOIP2015滚粗记
    HelloWorld!
    For the strivers ——
    【DP】最长公共子序列
    【DP】青蛙过河
    【DP+拓扑】关键子工程
    【线段树+向量】POJ 2991 Crane
    【线段树】POJ3225 Help with intervals
    【数学】test20170311
  • 原文地址:https://www.cnblogs.com/liuyongyu/p/14192618.html
Copyright © 2011-2022 走看看