Univalued Binary Tree

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:

Input:  root={1,1,1}
Output: true

Approach

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 not
    static boolean isSame(TreeNode rootint val) {
        // base case empty tree
        if (root == null)
            return true;

        // if value is not same then
        // return false
        if (root.val != val)
            return false;

        // call for both left subtree and right subtree
        return 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 valTreeNode leftTreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

C++

#include <bits/stdc++.h>
using namespace std;
//struct for treenode
struct 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 not
bool isSame(TreeNode *root,int val)
{
    //base case empty tree
    if(root==NULL)
              return true;

    //if value is not same then
    //return false
    if(root->data!=val)
        return false;

    //call for both left subtree and right subtree
    return 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";
  else
    cout<<"false";

  return 0;
  
}


No comments:

Post a Comment