A binary tree is univalued if every node in the tree has the same value.
Return
Return
true if and only if the given tree is univalued.Example:
Input: root={1,1,1}
Output: trueApproach
Java
public class UnivaluedBinaryTree {public static void main(String[] args) {TreeNode root = new TreeNode(1);root.left = new TreeNode(1);root.right = new TreeNode(1);System.out.println(isUnivalTree(root));}// function to check if the tree// have all value unique or notstatic boolean isSame(TreeNode root, int val) {// base case empty treeif (root == null)return true;// if value is not same then// return falseif (root.val != val)return false;// call for both left subtree and right subtreereturn isSame(root.left, val) && isSame(root.right, val);}static boolean isUnivalTree(TreeNode root) {if (root == null)return true;return isSame(root, root.val);}}class TreeNode {int val;TreeNode left;TreeNode right;TreeNode() {}TreeNode(int val) {this.val = val;}TreeNode(int val, TreeNode left, TreeNode right) {this.val = val;this.left = left;this.right = right;}}
C++
#include <bits/stdc++.h>using namespace std;//struct for treenodestruct TreeNode{int data;TreeNode *left;TreeNode *right;TreeNode(int data){this->data=data;this->left=NULL;this->right=NULL;}};//function to check if the tree//have all value unique or notbool isSame(TreeNode *root,int val){//base case empty treeif(root==NULL)return true;//if value is not same then//return falseif(root->data!=val)return false;//call for both left subtree and right subtreereturn isSame(root->left,val)&&isSame(root->right,val);}bool isUnivalTree(TreeNode* root){if(root==NULL)return true;return isSame(root,root->data);}int main(){TreeNode *root=new TreeNode(1);root->left=new TreeNode(1);root->right=new TreeNode(1);if(isUnivalTree(root))cout<<"true";elsecout<<"false";return 0;}
No comments:
Post a Comment