*LeetCode-Count Univalue Subtrees
2015-10-22 03:55
435 查看
想到了用递归判断子树中的count 并且记录目前位置所有数字是否unify 但是没有想好怎么存这些信息 怎么返回,count 可以作为static var 然后helper就返回boolean
注意count更新的条件 返回true false的条件很难归置好 注意判断left right 是否为null
返回false的条件就是首先 left right递归后都要是ture 同时left不是null的时候 value 要和root同 右边相同
假如这两个都没失败 那么count ++ 这一步其实是合并了好几种情况 假如左右有一个是null 或者都是null 那么加一 就是加上了root的那个子树
假如都不是null 并且都和root val相等 也是加上整个子树
public class Solution {
int count = 0;
public int countUnivalSubtrees(TreeNode root) {
helper ( root );
return count;
}
public boolean helper ( TreeNode root ){
if ( root == null )
return true;
boolean left = helper ( root.left );
boolean right = helper ( root.right );
if ( left && right ){
if ( root.left != null && root.val != root.left.val )
return false;
if ( root.right != null && root.val != root.right.val )
return false;
count ++;
return true;
}
return false;
}
}
注意count更新的条件 返回true false的条件很难归置好 注意判断left right 是否为null
返回false的条件就是首先 left right递归后都要是ture 同时left不是null的时候 value 要和root同 右边相同
假如这两个都没失败 那么count ++ 这一步其实是合并了好几种情况 假如左右有一个是null 或者都是null 那么加一 就是加上了root的那个子树
假如都不是null 并且都和root val相等 也是加上整个子树
public class Solution {
int count = 0;
public int countUnivalSubtrees(TreeNode root) {
helper ( root );
return count;
}
public boolean helper ( TreeNode root ){
if ( root == null )
return true;
boolean left = helper ( root.left );
boolean right = helper ( root.right );
if ( left && right ){
if ( root.left != null && root.val != root.left.val )
return false;
if ( root.right != null && root.val != root.right.val )
return false;
count ++;
return true;
}
return false;
}
}
相关文章推荐
- Use openCV lib in either Pre-built libraries or yourself build libs
- UGUI 帧动画插件
- Leetcode Verify Preorder Sequence in Binary Search Tree
- *LeetCode-Verify Preorder Sequence in Binary Search Tree
- Guess(精确2位浮点数)
- String StringBuilder StringBuffer 对比 总结得非常好
- UICollectionView创建实例
- 电子商务系统的设计与实现(七):前后端系统UI设计的一些思考
- UVA 1612 Guess
- UVA_1605: Building for UN
- CodeForces - 369E Valera and Queries(树状数组)
- IOS-UI控件大全
- 2015/10/21 UICollectionViewController 使用
- Under the Hood: Rebuilding Facebook for Android
- STL学习笔记-priority quene容器(优先级队列)
- STL学习笔记-quene容器(队列)
- STL学习笔记-deque容器(双端动态数组)
- DOTween 模仿NGUI Tween
- 【IOS 开发学习总结-OC-63】UIImage 与 CGImage,CGImageRef
- 黑马程序员--GUI