Home > AI > Data Structure > Tree > Binary Search Tree >

leetcode-965-Univalued Binary Tree

Solution (Java):

/**
 * Definition for a binary tree node.
 * public 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;
 *     }
 * }
 */
class Solution {
    public boolean isUnivalTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        
        int val = root.val;
        if (isUnivalSubTree(root.left, val) && isUnivalSubTree(root.right, val)) {
            return true;
        } else {
            return false;
        }
        
    }
    
    public boolean isUnivalSubTree(TreeNode root, int val) {
        if (root == null) {
            return true;
        }
        
        if (root.val != val) {
            return false;
        }
        if (isUnivalSubTree(root.left, val) && isUnivalSubTree(root.right, val)) {
            return true;
        }
        
        return false;
    }
}

Leave a Reply