> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/1001-2000/1373.-er-cha-sou-suo-zi-shu-de-zui-da-jian-zhi-he.md).

# 1373.二叉搜索子树的最大键值和

<https://leetcode-cn.com/problems/maximum-sum-bst-in-binary-tree/>

只要把前序遍历变成后序遍历，让 `traval` 函数把辅助函数做的事情顺便做掉

```python
class Solution:
    maxSum = 0

    def maxSumBST(self, root: TreeNode) -> int:
        #遍历函数
        def traval(root):
            if root == None:
                return [1, sys.maxsize, -sys.maxsize, 0]
            left = traval(root.left)
            right = traval(root.right)
            #res[0] 记录以 root 为根的二叉树是否是 BST，若为 1 则说明是 BST，若为 0 则说明不是 BST；
            #res[1] 记录以 root 为根的二叉树所有节点中的最小值；
            #res[2] 记录以 root 为根的二叉树所有节点中的最大值；
            #res[3] 记录以 root 为根的二叉树所有节点值之和。
            res = [0]*4
            #当左右子树都为BST，且左子都比root小，右子都比root大
            if left[0]==1 and right[0] == 1 and root.val > left[2] and root.val < right[1]:
                res[0]= 1
                res[1] = min(left[1], root.val)
                res[2] = max(right[2], root.val)
                res[3] = left[3] + right[3] + root.val
                self.maxSum = max(self.maxSum, res[3])
            else:
                res[0] = 0
            return res
				#开始遍历
        traval(root)
        return self.maxSum
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cai-sen-se.gitbook.io/leetcode/1001-2000/1373.-er-cha-sou-suo-zi-shu-de-zui-da-jian-zhi-he.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
