单值二叉树
如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。只有给定的树是单值二叉树时,才返回 true;否则返回 false。给定树的节点数范围是 [1, 100]。每个节点的值都是整数,范围为 [0, 99] 。相关标签:树, 深度优先搜索, 广度优先搜索, 二叉树。
Univalued Binary Tree
A binary tree is uni-valued if every node in the tree has the same value. Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise. The number of nodes in the tree is in the range [1, 100]. 0 <= Node.val < 100. Related Topics: Tree, Depth-First Search, Breadth-First Search, Binary Tree.
Input: root = [1,1,1,1,1,null,1]Output: true
Input: root = [2,2,2,5,2]Output: false
这题是单值二叉树,让我们判断一下二叉树里面是不是只有一种值,写个深度优先搜索非常容易判断!判断所有值是不是都等于根节点的值就可以了。
/*** Definition for a binary tree node.* struct TreeNode {* int val;* TreeNode *left;* TreeNode *right;* TreeNode() : val(0), left(nullptr), right(nullptr) {}* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}* };*/class Solution {public:bool isUnivalTree(TreeNode* root) {// dfs判断所有值是不是都等于根节点的值return dfs(root,root->val);}bool dfs(TreeNode* root,int val) {// 经典 二叉树如果是空的话则是成立的if(!root) return true;// 如果一旦出现不想等则不成立if(root->val!=val) return false;// 否则递归判断一下左右子树是不是也成立return dfs(root->left,val) && dfs(root->right,val);}};
/*** 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, val int) bool {if root == nil {return true}if root.Val != val {return false;}return dfs(root.Left,val) && dfs(root.Right,val)}
