(Java)leetcode-965 Univalued Binary Tree(单值二叉树)
题目描述
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.
思路
典型遍历问题。。。
代码
class Solution {
public boolean isUnivalTree(TreeNode root) {
if(root == null) return false;
return travelTree(root, root.val);
}
private boolean travelTree(TreeNode root, int val) {
if(root == null) return true;
if(root.val != val) return false;
return travelTree(root.left, val) && travelTree(root.right, val);
}
}
简洁版
int val = -1;
public boolean isUnivalTree(TreeNode root) {
if (root == null) return true;
if (val < 0) val = root.val;
return root.val == val && isUnivalTree(root.left) && isUnivalTree(root.right);
}
还没有评论,来说两句吧...