Leetcode 250.Count Univalue Subtrees
阿新 • • 發佈:2018-12-02
Leetcode 250.Count Univalue Subtrees
題目:
Given a binary tree, count the number of uni-value subtrees.
A Uni-value subtree means all nodes of the subtree have the same value.
For example:
Given binary tree,
5
/ \
1 5
/ \ \
5 5 5
return 4
解法:
這個題比較直接,就是通過遞迴找出左右子樹的節點值和父節點值均相同的子樹個數,比如結點 5 的樹的左子樹為空(判為true),右子樹的值是5,則證明滿足情況;同時葉子結點也是滿足情況的,因為葉子結點不含有子樹,所以左右子樹節點值都為 0
程式碼:
class Solution {
public:
bool DFS(TreeNode* root, int pre, int& ans)
{
if(!root) return true;
bool flag1 = DFS(root->left, root->val, ans);
bool flag2 = DFS(root->right, root->val, ans);
if(flag1 && flag2) ans++;
return (root->val == pre) && flag1 && flag2;
}
int countUnivalSubtrees(TreeNode* root) {
if(!root) return 0;
int ans = 0;
DFS(root, root->val, ans);
return ans;
}
};