{"id":6408,"date":"2020-03-08T01:28:27","date_gmt":"2020-03-08T09:28:27","guid":{"rendered":"https:\/\/zxi.mytechroad.com\/blog\/?p=6408"},"modified":"2020-03-08T11:04:44","modified_gmt":"2020-03-08T18:04:44","slug":"leetcode-1373-maximum-sum-bst-in-binary-tree","status":"publish","type":"post","link":"https:\/\/zxi.mytechroad.com\/blog\/tree\/leetcode-1373-maximum-sum-bst-in-binary-tree\/","title":{"rendered":"\u82b1\u82b1\u9171 LeetCode 1373. Maximum Sum BST in Binary Tree"},"content":{"rendered":"\n<figure class=\"wp-block-embed-youtube wp-block-embed is-type-video is-provider-youtube wp-embed-aspect-4-3 wp-has-aspect-ratio\"><div class=\"wp-block-embed__wrapper\">\n<iframe loading=\"lazy\" title=\"\u82b1\u82b1\u9171 LeetCode 1373. Maximum Sum BST in Binary Tree - \u5237\u9898\u627e\u5de5\u4f5c EP311\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/wrsdqcG7lTE?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe>\n<\/div><\/figure>\n\n\n\n<p>Given a&nbsp;<strong>binary tree<\/strong>&nbsp;<code>root<\/code>, the task is to return the maximum sum of all keys of&nbsp;<strong>any<\/strong>&nbsp;sub-tree which is also a Binary Search Tree (BST).<\/p>\n\n\n\n<p>Assume a BST is defined as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>The left subtree of a node contains only nodes with keys&nbsp;<strong>less than<\/strong>&nbsp;the node&#8217;s key.<\/li><li>The right subtree of a node contains only nodes with keys&nbsp;<strong>greater than<\/strong>&nbsp;the node&#8217;s key.<\/li><li>Both the left and right subtrees must also be binary search trees.<\/li><\/ul>\n\n\n\n<p><strong>Example 1:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/01\/30\/sample_1_1709.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> root = [1,4,3,2,4,2,5,null,null,null,null,null,null,4,6]\n<strong>Output:<\/strong> 20\n<strong>Explanation:<\/strong> Maximum sum in a valid Binary search tree is obtained in root node with key equal to 3.\n<\/pre>\n\n\n\n<p><strong>Example 2:<\/strong><\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"https:\/\/assets.leetcode.com\/uploads\/2020\/01\/30\/sample_2_1709.png\" alt=\"\"\/><\/figure>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> root = [4,3,null,1,2]\n<strong>Output:<\/strong> 2\n<strong>Explanation:<\/strong> Maximum sum in a valid Binary search tree is obtained in a single root node with key equal to 2.\n<\/pre>\n\n\n\n<p><strong>Example 3:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> root = [-4,-2,-5]\n<strong>Output:<\/strong> 0\n<strong>Explanation:<\/strong> All values are negatives. Return an empty BST.\n<\/pre>\n\n\n\n<p><strong>Example 4:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> root = [2,1,3]\n<strong>Output:<\/strong> 6\n<\/pre>\n\n\n\n<p><strong>Example 5:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-preformatted;crayon:false\"><strong>Input:<\/strong> root = [5,4,8,3,null,6,3]\n<strong>Output:<\/strong> 7\n<\/pre>\n\n\n\n<p><strong>Constraints:<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\"><li>Each tree has at most&nbsp;<code>40000<\/code>&nbsp;nodes..<\/li><li>Each node&#8217;s value is between&nbsp;<code>[-4 * 10^4&nbsp;, 4 * 10^4]<\/code>.<\/li><\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Solution: Recursion<\/strong><\/h2>\n\n\n\n<p>Time complexity: O(n)<br>Space complexity: O(h)<\/p>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">C++<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"C++\">\n\/\/ Author: Huahua\nclass Solution {\npublic:\n  int maxSumBST(TreeNode* root) {\n    int ans = 0;\n    dfs(root, &ans);\n    return ans;\n  }\nprivate:\n  \/\/ returns {lo, hi, sum, valid_bst}\n  tuple<int, int, int, bool> dfs(TreeNode* root, int* ans) {\n    if (!root) return {INT_MAX, INT_MIN, 0, true};\n    auto [ll, lh, ls, lv] = dfs(root->left, ans);\n    auto [rl, rh, rs, rv] = dfs(root->right, ans);\n    bool valid = lv && rv && root->val > lh && root->val < rl;    \n    int sum = valid ? ls + rs + root->val : -1;\n    *ans = max(*ans, sum);\n    return {min(ll, root->val), max(rh, root->val), sum, valid};\n  }\n};\n<\/pre>\n<\/div><\/div>\n\n\n\n<div class=\"responsive-tabs\">\n<h2 class=\"tabtitle\">Python3<\/h2>\n<div class=\"tabcontent\">\n\n<pre lang=\"python\">\n# Author: Huahua\nclass Solution:\n  def maxSumBST(self, root: TreeNode) -> int:    \n    # returns {lo, hi, sum, valid}\n    def dfs(node):\n      if not node: return (1e9, -1e9, 0, True)\n      ll, lh, ls, lv = dfs(node.left)\n      rl, rh, rs, rv = dfs(node.right)\n      v = lv and rv and node.val > lh and node.val < rl\n      s = ls + rs + node.val if v else -1\n      self.ans = max(self.ans, s)\n      return (min(ll, node.val), max(rh, node.val), s, v)\n    self.ans = 0\n    dfs(root)\n    return self.ans\n<\/pre>\n<\/div><\/div>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Given a&nbsp;binary tree&nbsp;root, the task is to return the maximum sum of all keys of&nbsp;any&nbsp;sub-tree which is also a Binary Search Tree (BST). Assume a&#8230;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[45],"tags":[217,17],"class_list":["post-6408","post","type-post","status-publish","format-standard","hentry","category-tree","tag-hard","tag-recursion","entry","simple"],"_links":{"self":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/6408","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/comments?post=6408"}],"version-history":[{"count":3,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/6408\/revisions"}],"predecessor-version":[{"id":6411,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/posts\/6408\/revisions\/6411"}],"wp:attachment":[{"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/media?parent=6408"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/categories?post=6408"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/zxi.mytechroad.com\/blog\/wp-json\/wp\/v2\/tags?post=6408"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}