如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。
只有给定的树是单值二叉树时,才返回 true;否则返回 false
输入:[1,1,1,1,1,null,1]
输出:true
输入:[2,2,2,5,2]
输出:false
解法:
深度优先搜索
PHP
/**
* Definition for a binary tree node.
* class TreeNode {
* public $val = null;
* public $left = null;
* public $right = null;
* function __construct($value) { $this->val = $value; }
* }
*/
class Solution {
/**
* @param TreeNode $root
* @return Boolean
*/
function isUnivalTree($root) {
return $this->dfs($root, $root->val);
}
function dfs($root, &$target) {
if ($root == null) {
return true;
}
if ($root->val != $target) {
return false;
}
return $this->dfs($root->left, $target) && $this->dfs($root->right, $target);
}
}
GO
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isUnivalTree(root *TreeNode) bool {
return dfs(root, &root.Val)
}
func dfs(root *TreeNode, target *int) bool {
if root == nil {
return true
}
if root.Val != *target {
return false
}
return dfs(root.Left, target) && dfs(root.Right, target)
}