题目:

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,

  1. 5
  2. / \
  3. 1 5
  4. / \ \
  5. 5 5 5

return 4.

链接: http://leetcode.com/problems/count-univalue-subtrees/

题解:

求Uni-value subtree的个数。对树来说这求count的首先思路就是递归了,不过这里要另外构造一个辅助函数来判断root为顶点的subtree是否是Uni-value subtree,假如是Uni-value的subtree,则结果可以+1,否则,我们返回递归求出的左子树的count和右节点的count。假如是Python的话可以一边计算一边返回。Java写起来可能稍微麻烦点。

Time Complexity - O(n), Space Complexity - O(n).

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int countUnivalSubtrees(TreeNode root) {
  12. if(root == null)
  13. return 0;
  14. if(root.left == null && root.right == null)
  15. return 1;
  16. if(root.left == null) {
  17. if(isUniValueSubtree(root))
  18. return countUnivalSubtrees(root.right) + 1;
  19. else
  20. return countUnivalSubtrees(root.right);
  21. } else if (root.right == null) {
  22. if(isUniValueSubtree(root))
  23. return countUnivalSubtrees(root.left) + 1;
  24. else
  25. return countUnivalSubtrees(root.left);
  26. } else {
  27. if(isUniValueSubtree(root))
  28. return countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right) + 1;
  29. else
  30. return countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
  31. }
  32. }
  33.  
  34. private boolean isUniValueSubtree(TreeNode root) {
  35. if(root == null)
  36. return true;
  37. if(root.left == null && root.right == null)
  38. return true;
  39. else if (root.left != null && root.right != null) {
  40. if(root.val == root.left.val && root.val == root.right.val)
  41. return isUniValueSubtree(root.left) && isUniValueSubtree(root.right);
  42. else
  43. return false;
  44. } else if (root.left == null) {
  45. if(root.right.val == root.val)
  46. return isUniValueSubtree(root.right);
  47. else
  48. return false;
  49. } else {
  50. if(root.left.val == root.val)
  51. return isUniValueSubtree(root.left);
  52. else
  53. return false;
  54. }
  55. }
  56. }

Update: 优化一下

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. public int countUnivalSubtrees(TreeNode root) {
  12. if(root == null)
  13. return 0;
  14. if(root.left == null && root.right == null)
  15. return 1;
  16. int res = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right) ;
  17. return isUniValueSubtree(root) ? res + 1 : res;
  18. }
  19.  
  20. private boolean isUniValueSubtree(TreeNode root) {
  21. if(root == null)
  22. return true;
  23. if(root.left == null && root.right == null)
  24. return true;
  25. if(isUniValueSubtree(root.left) && isUniValueSubtree(root.right)) {
  26. if(root.left != null && root.right != null)
  27. return (root.left.val == root.right.val) && (root.left.val == root.val);
  28. else if(root.left != null)
  29. return root.left.val == root.val;
  30. else
  31. return root.right.val == root.val;
  32. }
  33. return false;
  34. }
  35. }

Update: 再优化一下。注意判断两个子树是否都为Uni-value subtree的时候用了 '&',这样才能判断两个条件,否则第一个条件为false时就不判断第二个了。

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. private int count = 0;
  12. public int countUnivalSubtrees(TreeNode root) {
  13. if(root == null)
  14. return 0;
  15. isUniValueSubtree(root);
  16. return count;
  17. }
  18.  
  19. private boolean isUniValueSubtree(TreeNode root) {
  20. if(root == null)
  21. return true;
  22.  
  23. if(isUniValueSubtree(root.left) & isUniValueSubtree(root.right)) {
  24. if(root.left != null && root.left.val != root.val)
  25. return false;
  26. if(root.right != null && root.right.val != root.val)
  27. return false;
  28. count++;
  29. return true;
  30. }
  31. return false;
  32. }
  33. }

题外话:

这道题题号是250,马克一下。

二刷:

一刷写得比较250,现在要尝试不那么250。要做这道题我们首先要看清楚例子,以及弄明白什么是subtree。 subtree就是指,在一个tree里的某一个node,以及这个node的所有descendants.那么从题目给的例子里,我们复合条件的subtree有4个, 左边第三层里的两个"5"算其2, 右边第二层的"5 - 5",以及第三层的"5"也都算符合条件的subtree,所以我们返回4。 要注意root节点及右边第二层和第三层一起组成的"5-5-5"并不是subtree,这只能算一条root-to-leaf path。另外我们再看一个例子[1, 2, 3],这里作为leaf节点的2和3也分别都是符合条件的subtree,我们返回2。其实所有的leaf节点都是符合条件的。所以我们这道题的处理方法和https://leetcode.com/problems/balanced-binary-tree/ 有点像,都是自底向上进行判断。

  1. 这里我们先创建一个Global变量count, 也可以不用global变量而使用一个size为数组作为参数传递进辅助函数isUnival中。
  2. isUnival主要就是递归地自底向上判断tree是否为unival,也就是所有节点值均相等。有下面几种情况需要考虑
    1. root = null,这时候我们返回true。递归终止时,每个leaf节点都为true,所以null情况我们返回true
    2. 当左子树为unival并且右子树也为unival的时候
      1. 假如左右子节点都为空,则我们遇到leaf节点,合理,count++
      2. 假如左子节点或者右子节点不为空,但值又不与root的值相等时,root本身加左右子树形成的这个subtree不满足题意,我们返回false
      3. 否则,root及其descendants形成一个满足题意的subtree,我们把count++,记录下这个subtree
    3. 要注意判断左右子树是否为unival的时候,左子树和右子树都要判断,这里我们使用了一个'&'符号来避免短路条件判断。也可以分开写。

Java:

Time Complexity - O(n), Space Complexity - O(n).

  1. /**
  2. * Definition for a binary tree node.
  3. * public class TreeNode {
  4. * int val;
  5. * TreeNode left;
  6. * TreeNode right;
  7. * TreeNode(int x) { val = x; }
  8. * }
  9. */
  10. public class Solution {
  11. int count = 0;
  12.  
  13. public int countUnivalSubtrees(TreeNode root) {
  14. if (root == null) return 0;
  15. isUnival(root);
  16. return count;
  17. }
  18.  
  19. private boolean isUnival(TreeNode root) {
  20. if (root == null) return true;
  21. if (isUnival(root.left) & isUnival(root.right)) {
  22. if (root.left != null && root.left.val != root.val) return false;
  23. if (root.right != null && root.right.val != root.val) return false;
  24. count++;
  25. return true;
  26. }
  27. return false;
  28. }
  29. }

Reference:

https://leetcode.com/discuss/66805/my-java-solution-using-a-boolean-helper-function

https://leetcode.com/discuss/68057/very-easy-java-solution-post-order-recursion

https://leetcode.com/discuss/63286/7-line-accepted-code-in-java

https://leetcode.com/discuss/52210/c-one-pass-recursive-solution

https://leetcode.com/discuss/50241/recursive-java-solution-with-explanation

https://leetcode.com/discuss/50357/my-concise-java-solution

https://leetcode.com/discuss/50420/java-11-lines-added

https://leetcode.com/discuss/68057/very-easy-java-solution-post-order-recursion

https://github.com/google/google-java-format

https://leetcode.com/discuss/55213/my-ac-java-code

https://leetcode.com/discuss/53431/java-solution-with-dfs

https://leetcode.com/discuss/50452/ac-clean-java-solution

https://en.wikipedia.org/wiki/Tree_(data_structure)

https://leetcode.com/problems/balanced-binary-tree/

250. Count Univalue Subtrees的更多相关文章

  1. [LeetCode#250] Count Univalue Subtrees

    Problem: Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all ...

  2. [leetcode]250. Count Univalue Subtrees统计节点值相同的子树

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  3. [LeetCode] 250. Count Univalue Subtrees 计算唯一值子树的个数

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  4. [LC] 250. Count Univalue Subtrees

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  5. [Locked] Count Univalue Subtrees

    Count Univalue Subtrees Given a binary tree, count the number of uni-value subtrees. A Uni-value sub ...

  6. [LeetCode] Count Univalue Subtrees 计数相同值子树的个数

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  7. [Swift]LeetCode250.计数相同值子树的个数 $ Count Univalue Subtrees

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  8. LeetCode-Count Univalue Subtrees

    Given a binary tree, count the number of uni-value subtrees. A Uni-value subtree means all nodes of ...

  9. <Tree> 298 250 366 199(高频) 98(高频)

    298. Binary Tree Longest Consecutive Sequence 先序遍历,根左右.如果该节点的 value == 父节点value + 1, 则长度+1; 否则重置为1. ...

随机推荐

  1. IOS开发经验分享

    一些IOS开发的心得: 1) [Multiple Threads] IOS多线程注意, 所有的UI操作都必须在主线程上: Any code that will update the UI should ...

  2. Unity Camera属性

    Camera属性 1.Clear Flags 清除标记:决定屏幕的那部分将被清除.当使用多个相机来描绘不同的游戏景象时,利用它是非常方便的. 2.Background 背景:在镜头中的所有元素描绘完成 ...

  3. Feature Stapling in SharePoint 2010

    http://msdn.microsoft.com/en-us/library/bb861862(v=office.12).aspx http://gallery.technet.microsoft. ...

  4. VBS基础篇 - 堆栈

    VBS中的堆栈需要使用System.Collections.Stack '建立堆栈 Dim Stk : Set Stk = CreateObject("System.Collections. ...

  5. Week1 Team Homework #2: Introduction of each team member

    王洛书 我是来自浙江的王洛书.热爱历史,热爱美食,热爱代码,热爱博物馆.很喜欢软件工程这门课的上课方式,也很喜欢组里的这些同学.希望能大家一起努力,在这门课上真正地收获能力上的提升!   陈睿翊

  6. iOS VideoToolbox硬编H.265(HEVC)H.264(AVC):1 概述

    本文档尝试用Video Toolbox进行H.265(HEVC)硬件编码,视频源为iPhone后置摄像头.去年做完硬解H.264,没做编码,技能上感觉有些缺失.正好刚才发现CMFormatDescri ...

  7. 如何用jmeter对websock和protobuf进行压力测试

    1. 一个websocket插件官网地址 https://github.com/maciejzaleski/JMeter-WebSocketSampler 2. 可以用上述插件,也可以自己扩展,以实现 ...

  8. 关于sublime text的配置方法

    一个星期没有写博客了, 是时候来一波了 -------------------------------------------------------------------------------- ...

  9. Codeforces Gym 100342J Problem J. Triatrip 三元环

    题目链接: http://codeforces.com/gym/100342 题意: 求三元环的个数 题解: 用bitset分别统计每个点的出度的边和入度的边. 枚举每一条边(a,b),计算以b为出度 ...

  10. Matlab中unifrnd函数使用解析

    1.生成N阶[a,b]均匀分布数组 >> unifrnd(3,5,5,5) ans = 3.8651 4.6677 4.8115 4.3456 4.8560 4.0241 3.4079 3 ...