给定二叉树的根节点 root,找出存在于不同节点 A 和 B 之间的最大值 V,其中 V = |A.val - B.val|,且 A 是 B 的祖先。
(如果 A 的任何子节点之一为 B,或者 A 的任何子节点是 B 的祖先,那么我们认为 A 是 B 的祖先)
示例:
输入:[8,3,10,1,6,null,14,null,null,4,7,13]
输出:7
解释:
我们有大量的节点与其祖先的差值,其中一些如下:
|8 - 3| = 5
|3 - 7| = 4
|8 - 1| = 7
|10 - 13| = 3
在所有可能的差值中,最大值 7 由 |8 - 1| = 7 得出。
提示:
树中的节点数在 2 到 5000 之间。
每个节点的值介于 0 到 100000 之间。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-difference-between-node-and-ancestor
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int maxAncestorDiff(TreeNode* root) {
if(root == NULL)
{
return 0;
}
TreeNode* p = root;
TreeNode* r;
int sum = INT_MIN;
bool flag;
stack<TreeNode*> s1;
stack<TreeNode*> s2;
do
{
while(p != NULL)
{
s1.push(p);
s2.push(p);
p = p->left;
} //找到最左下角的节点,这个节点没有左子树
r = NULL;
flag = true;
//cout<<"s1.size() = "<<s1.size()<<endl;
//cout<<"s2.size() = "<<s2.size()<<endl;
while(!s1.empty() && flag)
{
p = s1.top();
if(p->right == r)
{
if(p->left == NULL && p->right == NULL) //叶子节点
{
//string tmp;
//int numtmp = 0;
vector<int> rec;
for(int i = 0; i<s1.size(); i++)
{
//tmp = tmp + s2.pop->val;
TreeNode* tmp = s2.top();
//numtmp = numtmp + (tmp->val)*pow(10,i);
rec.push_back(tmp->val);
//cout<<"numtmp = "<<numtmp<<endl;
s2.pop();
}
sort(rec.begin(), rec.end());
sum = max(sum, rec[rec.size()-1] - rec[0]);
//sum = sum + numtmp;
//cout<<"sum = "<<sum<<endl;
}
s2 =s1;
p = s1.top();
r = p;
s1.pop();
s2.pop();
}
else
{
p = p->right;
flag = false;
}
}
// return 1;
}while(!s1.empty());
return sum;
}
};