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

    Example :

    Input:  root = [5,1,5,5,5,null,5]
    
                  5
                 / 
                1   5
               /    
              5   5   5
    
    Output: 4

    题意:

    给定一棵二叉树,求所有节点都同值的二叉树。

    思路:

    dfs

    代码:

     1 class Solution {
     2     int result; 
     3     public int countUnivalSubtrees(TreeNode root) {
     4         result = 0; 
     5         helper(root); 
     6         return result;
     7     }
     8      
     9     private boolean helper(TreeNode node){
    10         if(node == null ) return true;
    11         
    12         boolean left = helper(node.left);
    13         boolean right = helper(node.right);
    14         
    15         if(left&&right){
    16         if ((node.left!= null && node.val != node.left.val) || (node.right!= null && node.val != node.right.val) ){
    17                 return false;
    18             }
    19             result++;
    20             return true;
    21         } 
    22         return false;
    23     }
    24 }
  • 相关阅读:
    update condition 字段报错
    Xshell连接Linux服务器总掉线
    sleep php函数
    ubuntu 16.04 镜像下载
    多线程Parallel和Task
    AngularJS 时间格式化
    正则表达式
    手机抓包
    内存泄漏
    字符集编码和排列规则
  • 原文地址:https://www.cnblogs.com/liuliu5151/p/9171274.html
Copyright © 2011-2022 走看看