解題思路
基本上就是 traverse 整棵樹,然後不斷紀錄這條 path 的最大值,以及更新 count 的次數。
程式碼
class Solution { public: void helper(TreeNode* root, int curMax, int& count) { if(root == nullptr) return; if(root->val >= curMax) count++; curMax = max(curMax, root->val); helper(root->left, curMax, count); helper(root->right, curMax, count); } int goodNodes(TreeNode* root) { int count = 0; helper(root, root->val, count); return count; } };
沒有留言:
張貼留言