代码随想录算法训练营第十六天|104. 二叉树的最大深度、559. N 叉树的最大深度、111. 二叉树的最小深度、222. 完全二叉树的节点个数

104. 二叉树的最大深度

    public int MaxDepth(TreeNode root) {
        return GetDepth(root);
    }
    public int GetDepth(TreeNode node) {
        if(node == null ) return 0;
        int leftDepth = GetDepth(node.left);
        int rightDepth = GetDepth(node.right);
        return leftDepth > rightDepth ? leftDepth + 1 : rightDepth + 1;
    }

559. N 叉树的最大深度

思路: 和104如出一辙

    public int MaxDepth(Node root) {
        if(root == null) return 0;
        return GetDepth(root);
    }
    public int GetDepth(Node node) {
        if(node == null ) return 0;
        int max = 0;
        for(int i = 0;i <node.children.ToList().Count;i++)
        {
            int len = GetDepth(node.children[i]);
            if(len > max) max = len;
        }

        return max+1;
    }

111. 二叉树的最小深度

思路: 和求最大深度一样,都是后序遍历,差别主要在于处理左右孩子不为空的逻辑。

public int MinDepth(TreeNode root) {
        if(root == null) return 0;
        return Depth(root);
    }
    public int Depth(TreeNode node) {
        if(node == null) return 0;
        int depth1 = MinDepth(node.left);
        int depth2 = MinDepth(node.right);
        if(node.left == null && node.right != null)
        {
            return depth2 +1;
        }
        if(node.right == null && node.left != null)
        {
            return depth1 +1;
        }

        return depth1 <depth2 ? depth1 +1: depth2 +1;
    }

222. 完全二叉树的节点个数

思路:当作普通二叉树求节点个数,也就是用层序遍历法。
按照完全二叉树的特性求解,暂时不想touch。

public int CountNodes(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> queue = new Queue<TreeNode>();
        queue.Enqueue(root);
        int sum = 0;
        while(queue.Count >0)
        {
            sum++;
            TreeNode node = queue.Dequeue();
            if(node.left != null) queue.Enqueue(node.left);
            if(node.right != null) queue.Enqueue(node.right);
        }
        return sum;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值