leetcode_333_最大 BST 子树@@二叉树

在这里插入图片描述

自顶向下

 TreeNode prev;
		
		private  boolean isBST(TreeNode root) {
			if(root==null) return true;
			boolean left = isBST(root.left);
			if(prev!=null&&prev.val>=root.val) {
	            //>=这题节点有可能相同,相同节点不是BST
				return false;
			}
			prev=root;
			boolean right = isBST(root.right);
			return left&&right;
		}
		
		private  int nodeCount(TreeNode root) {
	        if(root==null) return 0;
			return (nodeCount(root.left))+(nodeCount(root.right))+1;
		}

		public  int largestBSTSubtree(TreeNode root) {
	        if (root == null) return 0;
		    //每次判定是否是BST之前要初始化变量
		    prev=null;
			if(isBST(root)) {
				return nodeCount(root);
			}else {
				return Math.max(largestBSTSubtree(root.left), largestBSTSubtree(root.right));
			}
		}

自底向上

// 最大BST子树的信息
	private static class Info {
		public TreeNode root;// 根节点
		public int size;// 节点数量
		public int max;// 最大值
		public int min;// 最小值

		public Info(TreeNode root, int size, int max, int min) {
			this.root = root;
			this.size = size;
			this.max = max;
			this.min = min;
		}

	}

	public static Info getInfo(TreeNode root) {
		if (root == null)
			return null;
		if (root.left == null && root.right == null) {
			return new Info(root, 1, root.val, root.val);
		}

		Info left = getInfo(root.left);
		Info right = getInfo(root.right);
		if (left != null && right == null) {
			if (root.val > left.max && left.root == root.left) {
				return new Info(root, left.size + 1, root.val, left.min);
			}
			return left;
		} else if (left == null && right != null) {
			if (root.val < right.min && right.root == root.right) {
				return new Info(root, right.size + 1, right.max, root.val);
			}
			return right;
		} else {
			if (root.val > left.max && root.val < right.min && right.root == root.right && left.root == root.left) {
				return new Info(root, left.size + right.size + 1, right.max, left.min);
			}
			return left.size > right.size ? left : right;
		}

	}

	public static int largestBSTSubtree(TreeNode root) {
		return root == null ? 0 : getInfo(root).size;
	}

猜你喜欢

转载自blog.csdn.net/ruochen82155551/article/details/107597173