LeetCode Maximum Binary Tree

来源:互联网 发布:浏览器注入整人js脚本 编辑:程序博客网 时间:2024/06/05 08:44

Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:

  1. The root is the maximum number in the array.
  2. The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
  3. The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.

Construct the maximum tree by the given array and output the root node of this tree.

Example 1:

Input: [3,2,1,6,0,5]Output: return the tree root node representing the following tree:      6    /   \   3     5    \    /      2  0          \        1

Note:

  1. The size of the given array will be in the range [1,1000].
题解:
给定一个int型的数组,然后按照某种规则将其还原成一棵二叉树,其中的规则是,每次先找到数组中的最大值,将其作为根节点,然后再寻找其左右子树;其中这个节点所在的数组的左边为其左孩子,其右边为右孩子,依次类推。那么针对此题,我想到了用递归的方法来解,并且借鉴了另一道leetcode的题目,就是 

LeetCode Convert Sorted Array to Binary Search Tree,此题是将一个已经排好序的数组元素恢复成一棵二叉排序树,同样用递归,另外写一个函数,不停地调用其自身函数即可。这种递归的方法在树种中非常常用,希望能够借鉴学习到,为下次再遇到这种题做准备。

public class constructMaximumBinaryTree {public TreeNode constructMaximumBinaryTree(int[] nums){return getMax(0,nums.length - 1,nums);}public TreeNode getMax(int start,int end,int[] nums){if(start > end)   //用于递归结束的条件,这里一定要写对,而且递归函数往往在如果处先写上其结束条件,这里的结束条件是start > end,这是为了和后面的for循环呼应return null;int max = nums[start];int current = start;for(int i = start + 1; i <= end; i++){     if(nums[i] > max)     {     max = nums[i];     current = i;     }}        //寻找给定数组中的最大值TreeNode root = new TreeNode(max); //构建根节点root.left = getMax(start,current - 1,nums);  //对其左孩子采用同样的方法来递归,主要是改变其开始的上下标root.right = getMax(current + 1,end,nums);   //对其右孩子也采用同样的方法递归,改变其开始结束的上下标return root;                                 //注意这里是关键,其左右孩子的递归调用需要在这个函数主题内完成}}
这道题也给了我一些启示,对树的递归调用,往往会另写一个方法,然后在这个方法内递归写它自身,用于实现其左右孩子的建树。希望能够记住这种方法。



原创粉丝点击