[Locked] Count Univalue Subtrees
2016-02-24 12:21
561 查看
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,
return
分析:
有点像自低向上的动态规划,既然是自底向上,看来用递归访问树的节点无疑可以解决问题
代码:
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; }
相关文章推荐
- UITableViewHeaderFooterView的使用+自己主动布局
- handler机制的原理
- 【bzoj1570】[JSOI2008]Blue Mary的旅行 最大流
- openquery教程
- hibernate使用sqlQuery查询mysql数据库时别名问题
- 蓝牙学习之①:调戏小米手环
- iosUI开发
- iOS学习笔记59-UIView自带动画和核心动画(Core Animation)
- com.android.builder.packaging.DuplicateFile
- UE Category
- Flash builder 、flash cs6、 as 3.0研究
- argue, quarrel, debate, dispute,…
- UIView之userInteractionEnabled属性介绍
- 30. GNU Queue
- UIView的clipsTobounds属性
- Ext JS 6应用程序Build后出现“c is not a constructor return new c(a[0])”的处理
- java中String、StringBuffer、StringBuilder
- Ext JS 6应用程序Build后出现“c is not a constructor return new c(a[0])”的处理
- Ext JS 6应用程序Build后出现“c is not a constructor return new c(a[0])”的处理
- Ext JS 6应用程序Build后出现“c is not a constructor return new c(a[0])”的处理