题目链接:Leetcode 1448. 统计二叉树中好节点的数目
写了一个前序遍历,把当前节点和之前节点的最大值存到map数组中
递归
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
map<TreeNode*,int> mp;
int res=0;
void preorder(TreeNode* root,int pre)
{
if(!root) return ;
int v=root->val;
if(pre<=v)
{
mp[root]=v;
res++;
}
else
{
mp[root]=pre;
}
preorder(root->left,mp[root]);
preorder(root->right,mp[root]);
}
int goodNodes(TreeNode* root) {
preorder(root,INT_MIN);
return res;
}
};
迭代
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int goodNodes(TreeNode* root) {
int res=0;
stack<TreeNode*> st;
st.push(root);
map<TreeNode*,int> mp;
map<TreeNode*,TreeNode*> fa;
int pre=INT_MIN;
while(!st.empty())
{
root=st.top();
st.pop();
if (fa[root]==nullptr) pre=INT_MIN;
else
{
pre=mp[fa[root]];
}
if(pre<=root->val)
{
mp[root]=root->val;
res++;
}
else
{
mp[root]=pre;
}
if(root->right)
{
st.push(root->right);
fa[root->right]=root;
}
if(root->left)
{
st.push(root->left);
fa[root->left]=root;
}
}
return res;
}
};