1. 程式人生 > >LeetCode-Maximum Binary Tree

LeetCode-Maximum Binary Tree

Description: 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:

  • The size of the given array will be in the range [1,1000].

題意:給定一個一維陣列,裡面的元素代表樹的節點;現在要求構造一顆maximum tree;具體要求如下

  • 根節點的值為陣列中最大的那個數
  • 左子樹的根節點的值為最大數所在陣列位置左半部分陣列中的最大值
  • 右子樹的根節點的值為最大數所在陣列位置右半部分陣列中的最大值

解法:我們採用遞迴的方法來解決這道題目;首先從陣列中找到最大值最為根節點的值,然後依次找左子樹節點的值和右子樹節點的值;我們需要用一個數組來標記訪問過的元素,在判斷終止條件時有下面的兩種情況(其中,st表示要遍歷的陣列的開始座標,ed表示要遍歷的陣列的結束座標,visited陣列表示訪問過的陣列位置)

  • ed > st 表示沒有左節點或者右節點可以選擇
  • ed == st && visited[st] 僅有一個數可供選擇,但是已經被訪問過
/**
 * 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) {
        TreeNode root = null;
        boolean[] visited = new boolean[nums.length];
        root = getRoot(root, nums, visited, 0, nums.length - 1);
        return root;
    }
    
    private TreeNode getRoot(TreeNode root, int[] nums, boolean[] visited, int st, int ed) {
        if ((st == ed && visited[st]) || st > ed) {
            return null;
        }
        int index = st;
        root = new TreeNode(Integer.MIN_VALUE);
        for (int i = st; i <= ed; i++) {
            if (!visited[i] && nums[i] > root.val) {
                root.val = nums[i];
                index = i;
            }
        }
        visited[index] = true;
        root.left = getRoot(root.left, nums, visited, st, index - 1);
        root.right = getRoot(root.right, nums, visited, index + 1, ed);
        return root;
    }
}