原文链接 [每日 LeetCode] 965. Univalued Binary Tree
Description:
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.
Example 1:
```
Input: [1,1,1,1,1,null,1]
Output: true
Example 2:
```
Input: [2,2,2,5,2]
Output: false
思路:本题要求判断二叉树中每个结点的值是否相同,直接遍历即可,这里使用 DFS。
C++ 代码
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: bool isUnivalTree(TreeNode* root) { return dfs(root->left, root->val) && dfs(root->right, root->val); } bool dfs(TreeNode* root, int value){ if (!root) return true; if (root->val != value) return false; return dfs(root->left, value) && dfs(root->right, value); } };
运行时间:4ms
运行内存:10.8M
欢迎来到这里!
我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。
注册 关于