LeetCode654. 最大二叉树

题目来源:

https://leetcode-cn.com/problems/maximum-binary-tree/

题目描述:

LeetCode654. 最大二叉树_第1张图片

代码如下:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
	public TreeNode constructMaximumBinaryTree(int[] nums) {
		return constructMaximumBinaryTree(nums, 0, nums.length - 1);
	}

	public TreeNode constructMaximumBinaryTree(int[] nums, int left, int right) {
		if (left > right) {
			return null;
		}
		int maxIndex = findMaxIndex(nums, left, right);
		TreeNode node = new TreeNode(nums[maxIndex]);
		node.left = constructMaximumBinaryTree(nums, left, maxIndex - 1);
		node.right = constructMaximumBinaryTree(nums, maxIndex + 1, right);
		return node;
	}

	/**
	 * 返回最大值的下标
	 */
	public int findMaxIndex(int[] nums, int left, int right) {
		int maxIndex = left;
		for (int i = left + 1; i < right + 1; i++) {
			if (nums[i] > nums[maxIndex]) {
				maxIndex = i;
			}
		}
		return maxIndex;
	}
}

 

你可能感兴趣的:(LeetCode,654.,最大二叉树,LeetCode654.,最大二叉树,LeetCode,最大二叉树,二叉树)