題目:
A binary tree is univalued if every node in the tree has the same value.
Return true
if and only if the given tree is univalued.
Example:
Input: [1,1,1,1,1,null,1]Output: true
解法:
這題只是要判斷二元樹中所有val是否相同
一樣用遞迴解
程式碼:
/**
* 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 && root.Left.Val != root.Val) {
return false
}
if (root.Right != nil && root.Right.Val != root.Val) {
return false
}
return isUnivalTree(root.Left) && isUnivalTree(root.Right)
}
沒有留言:
張貼留言