Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to find out the maximum depth of python binary tree

Shulou Source: shulou.com Published: 2022-06-01 14:11:53 09月26日 Update

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!

Tags: Height maximum node depth subtree content leaf method more problem farthest longest helpless for this code reason this commonly used ideas skills Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno MySQL vpn OPPO Reno Docker macOS