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
.
分析:
有点像自低向上的动态规划,既然是自底向上,看来用递归访问树的节点无疑可以解决问题
代码:
bool dfs(TreeNode *node, int &count) { if(!node) return true; //一定要让保证其先递归,达到最底层节点,然后作后续处理 bool goodleft = dfs(node->left, count), goodright = dfs(node->right, count); //与左右节点值相同,且左右子树是值相同的树,则以该节点为根节点的树也是值相同的树 if(goodleft && goodright && (!node->left || node->val == node->left->val) && (!node->right || node->val == node->right->val)) { count++; return true; } return false; } int count(TreeNode *node) { int num = 0; dfs(node, num); return num; }