思路
maxDepth()
1. If tree is empty then return 0
2. Else
(a) Get the max depth of left subtree recursively i.e.,
call maxDepth( tree->left-subtree)
(a) Get the max depth of right subtree recursively i.e.,
call maxDepth( tree->right-subtree)
(c) Get the max of max depths of left and right
subtrees and add 1 to it for the current node.
max_depth = max(max dept of left subtree,
max depth of right subtree)
+ 1
(d) Return max_depth
代码
class TreeNode:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def maxdepth(root):
if root==None:
return 0
ldepth=maxdepth(root.left)
rdepth=maxdepth(root.right)
if(ldepth>rdepth):
return ldepth+1
else:
return rdepth+1
def main4():
root = TreeNode(1)
root.left= TreeNode(2)
root.right=TreeNode(3)
root.left.left=TreeNode(4)
root.left.right=TreeNode(5)
root.right.left=TreeNode(6)
root.right.right=TreeNode(7)
root.right.right.left=TreeNode(8)
print(maxdepth(root))
main4()