单值二叉树

如果二叉树每个节点都具有相同的值,那么该二叉树就是单值二叉树。只有给定的树是单值二叉树时,才返回 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.

  1. Input: root = [1,1,1,1,1,null,1]
  2. Output: true
  1. Input: root = [2,2,2,5,2]
  2. Output: false

这题是单值二叉树,让我们判断一下二叉树里面是不是只有一种值,写个深度优先搜索非常容易判断!判断所有值是不是都等于根节点的值就可以了。

  1. /**
  2. * Definition for a binary tree node.
  3. * struct TreeNode {
  4. * int val;
  5. * TreeNode *left;
  6. * TreeNode *right;
  7. * TreeNode() : val(0), left(nullptr), right(nullptr) {}
  8. * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
  9. * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
  10. * };
  11. */
  12. class Solution {
  13. public:
  14. bool isUnivalTree(TreeNode* root) {
  15. // dfs判断所有值是不是都等于根节点的值
  16. return dfs(root,root->val);
  17. }
  18. bool dfs(TreeNode* root,int val) {
  19. // 经典 二叉树如果是空的话则是成立的
  20. if(!root) return true;
  21. // 如果一旦出现不想等则不成立
  22. if(root->val!=val) return false;
  23. // 否则递归判断一下左右子树是不是也成立
  24. return dfs(root->left,val) && dfs(root->right,val);
  25. }
  26. };
  1. /**
  2. * Definition for a binary tree node.
  3. * type TreeNode struct {
  4. * Val int
  5. * Left *TreeNode
  6. * Right *TreeNode
  7. * }
  8. */
  9. func isUnivalTree(root *TreeNode) bool {
  10. return dfs(root,root.Val)
  11. }
  12. func dfs(root *TreeNode, val int) bool {
  13. if root == nil {
  14. return true
  15. }
  16. if root.Val != val {
  17. return false;
  18. }
  19. return dfs(root.Left,val) && dfs(root.Right,val)
  20. }