250. Count Univalue Subtrees

Given a binary tree, count the number of uni-value subtrees.

A Uni-value subtree means all nodes of the subtree have the same value.

For example:
Given binary tree,

              5
             / \
            1   5
           / \   \
          5   5   5

一刷
题解:注意

     5
     / \
    5   5

算3棵树

用DFS的原理,和boolean变量保存它的左右是否为univalue subtree.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    
    private int count = 0;
   
    public int countUnivalSubtrees(TreeNode root) {
        helper(root);
        return count;
    }
    
    private boolean helper(TreeNode node){
        if(node == null) return true;
        boolean left = helper(node.left);
        boolean right = helper(node.right);
        if(left && right){
            if(node.left!=null && node.val!=node.left.val) return false;
            if(node.right!=null && node.val!= node.right.val) return false;
            count++;
            return true;
        }
        return false;
    }
}

二刷
recursion

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    private int count = 0;
    
    public int countUnivalSubtrees(TreeNode root) {
        helper(root);
        return count;
    }
    
    private boolean helper(TreeNode root){
        if(root == null) return true;
        boolean left = helper(root.left);
        boolean right = helper(root.right);
        if(left && right){
            if(root.left!=null && root.val != root.left.val) return false;
            if(root.right!=null && root.val != root.right.val) return false;
            count++;
            return true;
        }
        return false;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,353评论 0 33
  • Given a binary tree, count the number of uni-value subtre...
    matrxyz阅读 2,720评论 0 0
  • 上次给大家介绍了“如何撰写一份高水平的求职简历?”,可能参加面试以后就会发现,几乎90%以上的面试,第一关都需要进...
    新锦成阅读 5,257评论 0 4
  • 桃花郡多生美人,百年来名流不绝于耳。或妖或艳,或清或雅,皆迎众家口味。不说樱桃小嘴儿,玲珑俏身段,有的不是外表,而...
    奇奇子阅读 3,511评论 6 5
  • 说过的话就像泼出去的水,再没有回旋的余地。 话不投机半句多。一句话就能使说话双方闹不愉快,甚至干起来。所以说...
    李二小姐阅读 2,870评论 0 0