二叉树的深度

2021-01-10  本文已影响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)
    }
}
上一篇下一篇

猜你喜欢

热点阅读