Table of contents
1. Question description
If each node of a binary tree has the same value, then the binary tree is a single-valued binary tree.
Returns true only if the given tree is a single-valued binary tree; otherwise, returns false.
2. Example
Example 1:
输入:[1,1,1,1,1,null,1]
输出:true
Example 2:
输入:[2,2,2,5,2]
输出:false
hint:
- The range of node number for a given tree is [1, 100].
- The value of each node is an integer, ranging from [0, 99].
Source: LeetCode
Link: https://leetcode.cn/problems/univalued-binary-tree
Copyright belongs to LeetCode Network. For commercial reprinting, please contact the official authorizer. For non-commercial reprinting, please indicate the source.
3. Ideas
Recursively compare the middle node and the left and right nodes, and return directly when there is a difference
4. Problems encountered
none
5. Specific implementation code
Code written by myself
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isUnivalTree(root *TreeNode) bool {
if root== nil{
return true
}
if root.Left != nil{
if root.Val != root.Left.Val{
return false
}
}
if root.Right != nil{
if root.Val != root.Right.Val{
return false
}
}
result := isUnivalTree(root.Left)
if !result{
return result
}
result = isUnivalTree(root.Right)
return result
}
6. Official solution
func isUnivalTree(root *TreeNode) bool {
return root == nil || (root.Left == nil || root.Val == root.Left.Val && isUnivalTree(root.Left)) &&
(root.Right == nil || root.Val == root.Right.Val && isUnivalTree(root.Right))
}
Author: LeetCode-Solution
Link: https://leetcode.cn/problems/univalued-binary-tree/solution/dan-zhi-er-cha-shu-by-leetcode-solution-15bn/
Source: LeetCode
Copyright belongs to the author. For commercial reprinting, please contact the author for authorization. For non-commercial reprinting, please indicate the source.
7 Source of question
。------swrici