# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
#递归法
def maxDepth_1(self, root: TreeNode) -> int:
def maxdepth(root):
if not root:
return 0
max_left = maxdepth(root.left)
max_right = maxdepth(root.right)
return max(max_left, max_right) + 1
return maxdepth(root)
#非递归法
def maxDepth(self, root: TreeNode) -> int:
#树的遍历一般非递归方法都是创建一个堆栈
if not root:
return 0
stack = [(root, 1)]
max_depth = 0
while stack:
root, current_depth = stack.pop()
max_depth = max(max_depth, current_depth)
if root.left:
stack.append((root.left, current_depth+1))
if root.right:
stack.append((root.right, current_depth+1))
return max_depth