LeetCode刷题第五天——统计同值子树

class Solution {
    private int count = 0;
    public int countUnivalSubtrees(TreeNode root) {
        help(root);
        return count;
    }
    public boolean help(TreeNode root) {
        boolean l = false;
        boolean r = false;
        if (root == null) {
            return false;
        }
        if (root.left != null) {
            l = help(root.left);
        }
        if (root.right != null) {
            r = help(root.right);
        }
        //叶子
        if (root.left == null && root.right == null) {
            ++count;
            return true;
        }
        //左子树null
        if (root.left == null && root.right != null) {
            if (root.right.val == root.val && r) {
                ++count;
                return true;
            }
            return false;
        }
        //右子树null
        if (root.right == null && root.left != null) {
            if (root.left.val == root.val && l) {
                ++count;
                return true;
            }
            return false;
        }
        //都不空
        if (root.left.val == root.right.val) {
            if (root.left.val == root.val && l && r) {
                count++;
                return true;
            }
        }
        return false;
    }
}

给定一个二叉树,统计该二叉树数值相同的子树个数。

同值子树是指该子树的所有节点都拥有相同的数值。

思路:

对于树结构首先考虑递归遍历:由根节点开始向左子树,右子树遍历。递归总体框架可以为:

- 异常情况返回

- 递归终止情况返回

- 递归调用

但是本题由于需要在左右子树都是同值的情况下才能判断当前子树是否是同值子树,所以需要把递归调用放最前面,首先通过递归调用走到叶子节点,进行判断。判断整体分为4种情况:

1. 当当前节点是叶子节点,count++;

2. 当当前节点的左子树空右子树不空,且右子树是同值子树且值等于当前root.val,count++,否则return false 表示当前子树的父子树已不再是同值子树。

3. 当当前节点的右子树空左子树不空,......

4. 当左右子树皆不空且值等于root.val,count++,return true

最终count存储的就是最终的结果!

猜你喜欢

转载自blog.csdn.net/m0_60388871/article/details/128688563