1. 程式人生 > >LeetCode 333. Largest BST Subtree

LeetCode 333. Largest BST Subtree

mean 排序 end largest its 大於 不為 ber 大二

Given a binary tree, find the largest subtree which is a Binary Search Tree (BST), where largest means subtree with largest number of nodes in it.

Note:
A subtree must include all of its descendants.

Follow up:
Can you figure out ways to solve it with O(n) time complexity?

此題的意思是找出一棵二叉樹裏的最大二叉搜索樹,即二叉樹內的一棵最大的滿足二叉搜索樹性質的子樹。

二叉搜索樹的定義是:二叉查找樹(Binary Search Tree),(又:二叉搜索樹,二叉排序樹)它或者是一棵空樹,或者是具有下列性質的二叉樹: 若它的左子樹不空,則左子樹上所有結點的值均小於它的根結點的值; 若它的右子樹不空,則右子樹上所有結點的值均大於它的根結點的值; 它的左、右子樹也分別為二叉排序樹。

題解:

采用後序遍歷,先計算出子樹的解。對於每個子樹,計算出的結果res是一個integer的長度為4的數組。res[0]:是否是二叉搜索樹,res[1]該棵二叉搜索樹的大小,res[2]該二叉搜索樹的最小值,res[3]該二叉搜索樹的最大值。

然後判斷當前子樹是否為二叉搜索樹,當左子樹,右子樹不為二叉搜索樹,或者左子樹的最大值大於等於root的值,或者右子樹的最小值小等於root的值時,當前子樹不是二叉搜索樹。

否則當前子樹是二叉搜索樹。

時間復雜度O(n)

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int largestBSTSubtree(TreeNode root) {
        if(root == null
) return 0; Integer[] res = dfs(root); return res[1]; } public Integer[] dfs(TreeNode root) { if(root == null) return new Integer[]{1, 0, null, null}; if(root.left == null && root.right == null) return new Integer[]{1, 1, root.val, root.val}; Integer[] left = dfs(root.left); Integer[] right = dfs(root.right); if(left[0] == 0 || right[0] == 0 || (left[3] != null && left[3] >= root.val) || (right[2] != null && right[2] <= root.val)) { return new Integer[]{0, Math.max(left[1], right[1]), null, null}; } return new Integer[]{1, 1 + left[1] + right[1], left[2] == null ? root.val : left[2], right[3] == null ? root.val : right[3]}; } }

LeetCode 333. Largest BST Subtree