zoukankan      html  css  js  c++  java
  • 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
    

    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;
        }
    }
  • 相关阅读:
    csuoj 漫漫上学路
    sql函数
    sql基本
    查看webdriver API
    Jmeter应用-接口测试
    http协议
    Jmeter .jmx 改为.jtl
    Jmeter遇到打不开的问题
    测试要点
    apt-get安装mysql
  • 原文地址:https://www.cnblogs.com/joannacode/p/5952209.html
Copyright © 2011-2022 走看看