C++程序中,在二叉树中找到最大子树和,使得子树也是BST
在这个问题中,我们给定一棵二叉树BT。我们的任务是创建一个程序,在二叉树中找到最大子树和,使得子树也是BST。
二叉树有一个特殊条件,即每个节点最多可以有两个子节点。
二叉搜索树是一棵树,其中所有节点都遵循以下属性
左子树的键值小于其父节点(根节点)的键值。
右子树的键值大于或等于其父节点(根节点)的键值。
让我们举个例子来理解这个问题,
输入
输出
32
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
解释
这里,我们有两个是BST的子树。它们的和是,
7 + 3 + 22 = 32 6 + 5 + 17 = 28 Maximum = 32.
解决方案
解决这个问题的一个简单方法是遍历树数据结构,然后在每个节点处检查其子节点是否可以形成二叉搜索树。如果我们找到所有构成BST的节点的和,然后返回找到的所有BSTSum中的最大值。
示例
程序说明解决方案的工作原理,
#include <bits/stdc++.h> using namespace std; int findMax(int a, int b){ if(a > b) return a; return b; } int findMin(int a, int b){ if(a > b) return b; return a; } struct Node { struct Node* left; struct Node* right; int data; Node(int data){ this−>data = data; this−>left = NULL; this−>right = NULL; } }; struct treeVal{ int maxVal; int minVal; bool isBST; int sum; int currMax; }; treeVal CalcBSTSumTill(struct Node* root, int& maxsum){ if (root == NULL) return { −10000, 10000, true, 0, 0 }; if (root−>left == NULL && root−>right == NULL) { maxsum = findMax(maxsum, root−>data); return { root−>data, root−>data, true, root−>data, maxsum }; } treeVal LeftSTree = CalcBSTSumTill(root−>left, maxsum); treeVal RightSTree = CalcBSTSumTill(root−>right, maxsum); treeVal currTRee; if (LeftSTree.isBST && RightSTree.isBST && LeftSTree.maxVal < root−>data && RightSTree.minVal > root−>data) { currTRee.maxVal = findMax(root−>data, findMax(LeftSTree.maxVal, RightSTree.maxVal)); currTRee.minVal = findMin(root−>data, findMin(LeftSTree.minVal, RightSTree.minVal)); maxsum = findMax(maxsum, RightSTree.sum + root−>data + LeftSTree.sum); currTRee.sum = RightSTree.sum + root−>data + LeftSTree.sum; currTRee.currMax = maxsum; currTRee.isBST = true; return currTRee; } currTRee.isBST = false; currTRee.currMax = maxsum; currTRee.sum = RightSTree.sum + root−>data + LeftSTree.sum; return currTRee; } int CalcMaxSumBST(struct Node* root){ int maxsum = −10000; return CalcBSTSumTill(root, maxsum).currMax; } int main(){ struct Node* root = new Node(10); root−>left = new Node(12); root−>left−>right = new Node(7); root−>left−>right−>left = new Node(3); root−>left−>right−>right = new Node(22); root−>right = new Node(6); root−>right−>left = new Node(5); root−>right−>left−>right = new Node(17); cout<<"The maximum sub−tree sum in a Binary Tree such that the sub−tree is also a BST is "<<CalcMaxSumBST(root); return 0; }
输出
The maximum sub−tree sum in a Binary Tree such that the sub−tree is also a BST is 32
广告