965.单值二叉树
题目
![](https://filescdn.proginn.com/b4affb19703adac4efd651ebce084818/1daae7d47e485d13b5a02f350a6f5b0d.webp)
题目链接:https://leetcode.cn/problems/univalued-binary-tree/
题解
直接使用深度优先搜索即可,对二叉树进行递归遍历。
class Solution {
public boolean isUnivalTree(TreeNode root) {
if (root == null) {
return true;
}
return isUnivalTree(root, root.val);
}
public boolean isUnivalTree(TreeNode root, int val) {
if (root == null) {
return true;
}
return root.val == val && isUnivalTree(root.left, val) && isUnivalTree(root.right, val);
}
}
结果
![](https://filescdn.proginn.com/ba9f84f8bbff4d5eb9e954be5b0a2b8a/82c2cc6411f354b833c0ece77251c410.webp)
-
评论