LeetCode Count Univalue Subtrees
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode Count Univalue Subtrees相关的知识,希望对你有一定的参考价值。
原题链接在这里:https://leetcode.com/problems/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,
5
/ 1 5
/ \ 5 5 5
return 4
.
helper funtion 来返回当前tree 是不是 unitree.
两个终止条件一个不能少,若root == null 返回true. 若root是叶子节点, res[0]++, 返回true.
recursion时left保存左子树是否是unitree, right保存右子树是否是unitree.
若都是检查root的val 和左右是否相等,
若想等, res[0]++, 返回true.
AC Java:
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 int [] res = {0}; 13 helper(root, res); 14 return res[0]; 15 } 16 17 private boolean helper(TreeNode root, int [] res){ 18 if(root == null){ 19 return true; 20 } 21 22 if(root.left == null && root.right == null){ 23 res[0]++; 24 return true; 25 } 26 27 boolean left = helper(root.left, res); 28 boolean right = helper(root.right, res); 29 if(left && right && (root.left == null || root.left.val == root.val) && (root.right == null || root.right.val == root.val)){ 30 res[0]++; 31 return true; 32 } 33 return false; 34 } 35 }
以上是关于LeetCode Count Univalue Subtrees的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Count Univalue Subtrees 计数相同值子树的个数
[LeetCode] 250. Count Univalue Subtrees 计算唯一值子树的个数