• [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;
    }
  • 相关阅读:
    【Angular2】ng2的开始_组件
    【js框架】随笔
    【sublime text3】个性化定制
    PLSQL中文乱码问题
    Microsoft office 2010密钥
    node_oracle连接
    oracle安装配置
    Logging in Java
    Java 基础
    Hibernate
  • 原文地址:https://www.cnblogs.com/littletail/p/5208067.html
Copyright © 2020-2023  润新知