zoukankan      html  css  js  c++  java
  • [Locked] Count Univalue Subtrees

    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.

    分析:

      有点像自低向上的动态规划,既然是自底向上,看来用递归访问树的节点无疑可以解决问题

    代码:

    bool dfs(TreeNode *node, int &count) {
        if(!node)
            return true;
        //一定要让保证其先递归,达到最底层节点,然后作后续处理
        bool goodleft = dfs(node->left, count), goodright = dfs(node->right, count);
        //与左右节点值相同,且左右子树是值相同的树,则以该节点为根节点的树也是值相同的树
        if(goodleft && goodright && (!node->left || node->val == node->left->val) && (!node->right || node->val == node->right->val)) {
            count++;
            return true;
        }
        return false;
    }
    int count(TreeNode *node) {
        int num = 0;
        dfs(node, num);
        return num;
    }
  • 相关阅读:
    Delphi中Chrome Chromium、Cef3学习笔记(五)
    java ->IO流_File类
    java ->递归
    java-> 分包分层
    java ->JDBC
    java -> 异常类与自定义异常
    java ->斗地主洗牌
    java -> map接口
    java ->Set接口
    java -> List接口
  • 原文地址:https://www.cnblogs.com/littletail/p/5208067.html
Copyright © 2011-2022 走看看