559. Maximum Depth of N-ary Tree

1.若为二叉树:
Time: O(N) Proportional to input nodes, Iterates all nodes once.
Space: O(H) Maximum nodes within the temporary call stack

Base Case: 当Node为空的时候,返回高度为0

Recursive Rule精确版本 :
传递: 左右孩子
向下索取:下一层的左子树和右子树索取最高深度
向上返回:选择更高的深度并且加上当前层数的高度 (+1) 。最终返回。

Recursive Rule说人话:
谁高取谁,并加一

def maxDepth(self, root):
        if not root:
            return 0
        return 1+max(self.maxDepth(root.left),self.maxDepth(root.right))
def maxDepth(self, root):
        if not root:
            return 0
        depth=0
        queue = collections.deque()
        queue.append(root)
        while queue:
            depth += 1
            for _ in range(len(queue)):
                node = queue.popleft()
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
        return depth

2.N叉树:
二叉树每层比对左右孩子,那么N叉树我们在每一层创建一个临时的List用来保存当前Node的所有子孩子传递上来的高度,取其最大返回

class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        if not root.children: return 1
        height = []
        for node in root.children:
            height.append(self.maxDepth(node))
        return max(height) + 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值