In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/01 Report--
How to find out the maximum depth of python binary tree, I believe that many inexperienced people do not know what to do about it. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
[title]
Given a binary tree, find out its maximum depth.
The depth of the binary tree is the number of nodes on the longest path from the root node to the furthest leaf node.
Note: a leaf node is a node that does not have child nodes.
Example:
Given binary tree [3pc9pr 20pr nullpr nullpr 15pc7]
three
/\
9 20
/\
15 7
Returns its maximum depth of 3.
[ideas]
Using the common solution of binary tree: the maximum height of left subtree and the maximum height of right subtree are obtained recursively (if a subtree is empty, then the height is 0), then the height of this layer is the maximum height of both + 1.
[code]
Python version
# Definition for a binary tree node.
# class TreeNode:
# def _ _ init__ (self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
Class Solution:
Def maxDepth (self, root: TreeNode)-> int:
# Node is None, and the return height is 0
If not root:
Return 0
Left_depth, right_depth = 0,0
# get the height of the left subtree
If root.left:
Left_depth = self.maxDepth (root.left)
# get the height of the right subtree
If root.right:
Right_depth = self.maxDepth (root.right)
Return max (left_depth, right_depth) + 1
After reading the above, do you know how to find the maximum depth of the python binary tree? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.