日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 250. Count Univalue Subtrees

發布時間:2024/4/17 编程问答 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 LeetCode 250. 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.

題解:

bottom-up recursion. dfs返回當前root下是不是univalue tree.

Time Complexity: O(n).

Space: O(logn). height of tree.

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 class Solution { 11 public int countUnivalSubtrees(TreeNode root) { 12 int [] res = {0}; 13 dfs(root, res); 14 return res[0]; 15 } 16 17 private boolean dfs(TreeNode root, int [] res){ 18 if(root == null){ 19 return true; 20 } 21 22 boolean left = dfs(root.left, res); 23 boolean right = dfs(root.right, res); 24 if(left && right){ 25 if(root.left!=null && root.left.val!=root.val){ 26 return false; 27 } 28 29 if(root.right!=null && root.right.val!=root.val){ 30 return false; 31 } 32 33 res[0]++; 34 return true; 35 } 36 37 return false; 38 } 39 }

類似Longest Univalue Path.

轉載于:https://www.cnblogs.com/Dylan-Java-NYC/p/5187437.html

總結

以上是生活随笔為你收集整理的LeetCode 250. Count Univalue Subtrees的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。