美文网首页
二叉树的深度

二叉树的深度

作者: 九日火 | 来源:发表于2021-01-10 14:02 被阅读0次
    class ListNode:
        def __init__(self, x):
            self.root = x
            self.left = None
            self.right = None
    
    
    class Solution:
        def TreeDepth(self, pRoot):
            if pRoot == None:
                return 0
            else:
                return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
    
    package main
    
    type ListNode struct {
        Val    int
        Left   *ListNode
        Right  *ListNode
    }
    
    func MaxDepth(Root *ListNode) int {
        max := 0
        if Root == nil {
            return 0
        } else {
            return Max(MaxDepth(Root.Left), MaxDepth(Root.Right)) + 1
        }
    }
    
    func Max(a, b int) int {
        if a >= b {
            return a
        }
        return b
    }
    
    func MaxDepth1(Root *ListNode) int {
        max := 0
        var dfs func(Root *ListNode, level int)
        dfs = func(Root *ListNode, level int) {
            if Root == nil {
                return
            }
            if level > max {
                max = level
            }
            dfs(Root.Left, level+1)
            dfs(Root.Right, level+1)
        }
    }
    

    相关文章

      网友评论

          本文标题:二叉树的深度

          本文链接:https://www.haomeiwen.com/subject/cyucaktx.html