leetcode-1373-Maximum Sum BST in Binary Tree
问题
Given a binary tree root
, the task is to return the maximum sum of all keys of any sub-tree which is also a Binary Search Tree (BST).
Assume a BST is defined as follows:
- The left subtree of a node contains only nodes with keys less than the node’s key.
- The right subtree of a node contains only nodes with keys greater than the node’s key.
- Both the left and right subtrees must also be binary search trees.
Example 1:
1 | Input: root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6] |
Example 2:
1 | Input: root = [4,3,null,1,2] |
Example 3:
1 | Input: root = [-4,-2,-5] |
Example 4:
1 | Input: root = [2,1,3] |
Example 5:
1 | Input: root = [5,4,8,3,null,6,3] |
Constraints:
- Each tree has at most
40000
nodes.. - Each node’s value is between
[-4 * 10^4 , 4 * 10^4]
.
分析
看到树的问题第一反应应该是递归。那么对于一颗子树而言,它是二叉搜索树的条件是:
- 左子树为空,或者左子树是二叉搜索树且左子树所有节点中的最大值小于子树的根节点的值。
- 右子树为空,或者右子树是二叉搜索树且右子树所有节点中的最小值大于子树的根节点的值。
另外,题目中要求我们求BST的SUM,因此我们递归遍历时需要返回的值就有四个,是否为BST、子树的最小节点值、子树的最大节点值、子树的所有节点的值的综合。我们可以使用一个vector\
代码
1 | /** |
Author: Hatton.Liu
Link: http://hattonl.github.io/2020/03/11/leetcode-1373/
License: 知识共享署名-非商业性使用 4.0 国际许可协议