首页 > 其他 > 详细

leetcode 250 Count Univalue Subtrees

时间:2019-08-16 09:21:46      阅读:64      评论:0      收藏:0      [点我收藏+]

技术分享图片

 

思路很简单,存在最优子结构,用递归自上至下解即可。

如何判断当前root所代表的树是否为uni-value subtree?

1. 检查root和left,right值是否一致

2. left子树和right子树是否都为uni-value

注意第二步,可能left,right为空,写if时要注意

 1 class Solution {  
 2     private int count;
 3     public int countUnivalSubtrees(TreeNode root) {  
 4         uni(root);  
 5         return count;  
 6     }  
 7       
 8     boolean uni(TreeNode root) {  
 9         if(root == null)  
10             return true;  
11         if(root.left ==null && root.right == null) {  
12             count++;  
13             return true;  
14         }  
15         bool left = uni(root.left);  
16         bool right = uni(root.right);  
17         if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)) {  
18             count++;  
19             return true;  
20         }  
21         return false;  
22     }  
23 }

 

leetcode 250 Count Univalue Subtrees

原文:https://www.cnblogs.com/hwd9654/p/11361422.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!