题目地址:Univalued Binary Tree - LeetCode
Acceptance: 67.6%
Difficulty: Easy
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 1:
Input: [1,1,1,1,1,null,1]
Output: true
Example 2:
Input: [2,2,2,5,2]
Output: false
Note:
The number of nodes in the given tree will be in the range [1, 100].
Each node’s value will be an integer in the range [0, 99].
这题的意思是判断一个二叉树的所有节点的值是否相同。
python3代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isUnivalTree(self, root: TreeNode) -> bool:
if root==None:
return True
if (root.left!=None and root.left.val!=root.val) or (root.right!=None and root.right.val!=root.val):
return False
return self.isUnivalTree(root.left) and self.isUnivalTree(root.right)
Java代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root==null){
return true;
}
if( (root.left!=null && root.left.val!=root.val) || (root.right!=null && root.right.val!=root.val)){
return false;
}
return isUnivalTree(root.left) && isUnivalTree(root.right);
}
}
java运行就是比Python快,只要2ms。
官方参考解法:
class Solution(object):
def isUnivalTree(self, root):
left_correct = (not root.left or root.val == root.left.val
and self.isUnivalTree(root.left))
right_correct = (not root.right or root.val == root.right.val
and self.isUnivalTree(root.right))
return left_correct and right_correct