LeetCode 250. Count Univalue Subtrees
原题链接在这里:https://leetcode.com/problems/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
.
题解:
bottom-up recursion. dfs返回当前root下是不是univalue tree.
Time Complexity: O(n).
Space: O(logn). height of tree.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 class Solution { 11 public int countUnivalSubtrees(TreeNode root) { 12 int [] res = {0}; 13 dfs(root, res); 14 return res[0]; 15 } 16 17 private boolean dfs(TreeNode root, int [] res){ 18 if(root == null){ 19 return true; 20 } 21 22 boolean left = dfs(root.left, res); 23 boolean right = dfs(root.right, res); 24 if(left && right){ 25 if(root.left!=null && root.left.val!=root.val){ 26 return false; 27 } 28 29 if(root.right!=null && root.right.val!=root.val){ 30 return false; 31 } 32 33 res[0]++; 34 return true; 35 } 36 37 return false; 38 } 39 }
AC C++:
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 int countUnivalSubtrees(TreeNode* root) { 15 int res = 0; 16 dfs(root, res); 17 return res; 18 } 19 20 bool dfs(TreeNode* root, int& res){ 21 if(!root){ 22 return true; 23 } 24 25 bool left = dfs(root->left, res); 26 bool right = dfs(root->right, res); 27 if(left && right){ 28 if(root->left && root->left->val != root->val){ 29 return false; 30 } 31 32 if(root->right && root->right->val != root->val){ 33 return false; 34 } 35 36 res++; 37 return true; 38 } 39 40 return false; 41 } 42 };