[LeetCode250]Count Univalue Subtrees
来源:互联网 发布:unity3d 重力感应 编辑:程序博客网 时间:2024/04/29 14:49
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 5return 4.Hide Tags Tree
一如既往,这种题用recursion会简单很多。
根据例子,最后的node也会算做这个univalue subtree。
所以利用一个helper function判断每个left subtree 和right subtree 是不是univalue的。 如果两边都是,则判断root->val 是否等于left->val, right->val如果满足,则increase cnt, 否则返回0。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: bool isUni(TreeNode* node, int&cnt){ if(!node) return true; bool left = isUni(node->left, cnt); bool right = isUni(node->right, cnt); if(left && right){ if(node->left && node->left->val != node->val) return false; else if(node->right && node->right->val != node->val) return false; else{ ++cnt; return true; } } return false; } int countUnivalSubtrees(TreeNode* root) { if(!root) return 0; int cnt = 0; isUni(root,cnt); return cnt; }};
0 0
- [LeetCode250]Count Univalue Subtrees
- Leetcode: Count Univalue Subtrees
- *LeetCode-Count Univalue Subtrees
- Count Univalue Subtrees
- Count Univalue Subtrees
- 250. Count Univalue Subtrees
- 250. Count Univalue Subtrees
- Leetcode 250Count Univalue Subtrees
- [LeetCode 265] Count Univalue Subtrees
- LeetCode 250. Count Univalue Subtrees
- LeetCode 题解(265) : Count Univalue Subtrees
- [leetcode] 250. Count Univalue Subtrees 解题报告
- Leetcode 250. Count Univalue Subtrees (Medium) (cpp)
- [Leetcode] 250. Count Univalue Subtrees 解题报告
- LeetCode 250. Count Univalue Subtrees(单值子树)
- [leetcode 250]Count Univalue Subtrees ------元素都相同的子树个数
- hdu5524 Subtrees
- 687. Longest Univalue Path
- **LeetCode-Substring with Concatenation of All Words
- 学习Python (五)
- Matlab和C程序的备忘2
- 10 条提升 Android 性能的建议
- Linux C语言中sscanf 的详细用法
- [LeetCode250]Count Univalue Subtrees
- S5pv210 HDMI 接口驱动框架
- “南大软院大神养成计划“_第十天的学习“
- 上谷歌google的简单方法
- [LeetCode251]Flatten 2D Vector
- 如何将数据添加到自定义的DataTable中并赋值给list实现打印功能。
- C#里的时间戳
- Android使用Httpclient网络请求,get,post方法
- SpringMVC简介及搭建流程