码迷,mamicode.com
首页 > 其他好文 > 详细

250. Count Univalue Subtrees

时间:2016-10-12 13:54:19      阅读:103      评论:0      收藏:0      [点我收藏+]

标签:

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

 

return 4.

 

Hide Tags
 Tree
 
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    //post order;
    int max = 1;
    public int countUnivalSubtrees(TreeNode root) {
        if(root == null) return 0;
        if(root.left == null && root.right == null) return 1;
        int res = countUnivalSubtrees(root.left) + countUnivalSubtrees(root.right);
        return isUniTree(root) ? res +1 : res;
    }
    public boolean isUniTree(TreeNode root){
        if(root == null) return true;
        if(root.left == null && root.right == null) return true;
        if(isUniTree(root.left) && isUniTree(root.right)){
            if(root.left != null && root.right != null){
                return (root.left.val == root.right.val && root.right.val == root.val);
            }else if(root.left != null)
                return root.left.val == root.val;
             else
                return root.right.val == root.val;
        }
        return false;
    }
}

 

250. Count Univalue Subtrees

标签:

原文地址:http://www.cnblogs.com/joannacode/p/5952209.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!