Count Good Nodes in Binary Tree(C++统计二叉树中好节点的数目)

野性酷女 2023-01-03 12:51 162阅读 0赞

解题思路:

(1)记录每次节点最大值的变化次数

(2)使用值传递而不是址传递,类似回溯法

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. void pre_order(TreeNode *root,int max,int &count) {
  15. if(root==NULL) return;
  16. if(root->val>=max) {
  17. max=root->val;
  18. count++;
  19. };
  20. pre_order(root->left,max,count);
  21. pre_order(root->right,max,count);
  22. }
  23. int goodNodes(TreeNode* root) {
  24. if(root==NULL) return 0;
  25. int max=root->val,count=0;
  26. pre_order(root,max,count);
  27. return count;
  28. }
  29. };

发表评论

表情:
评论列表 (有 0 条评论,162人围观)

还没有评论,来说两句吧...

相关阅读