# Leetcode 965. Univalued Binary Tree (0ms) ###### tags: `Leetcode` 題目 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. Example 1: Input: root = [1,1,1,1,1,null,1] Output: true Example 2: Input: root = [2,2,2,5,2] Output: false 解法: 1.分五種情況 a.root == NULL b.左右子節點都是NULL c.左節點是NULL、右節點不是NULL d.把c.相反 e.左右都不是NULL ====================== ``` /** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ bool isUnivalTree(struct TreeNode* root){ if(root == NULL) return true; if(root->left == NULL && root->right == NULL) return true; if(root->left != NULL && root->right == NULL) { if(root->left->val == root->val) return isUnivalTree(root->left); else return false; } if(root->right != NULL && root->left == NULL) { if(root->right->val == root->val) return isUnivalTree(root->right); else return false; } if(root->val == root->left->val && root->val == root->right->val) return isUnivalTree(root->left) & isUnivalTree(root->right); else return false; } ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up