您的位置:首页 > 产品设计 > UI/UE

*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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: