[Leetcode Binary Tree Series] 3 Maximum depth of binary tree

344d69c84a85bfcc2eac3c0807045139.gif


 This article involves knowledge points 

  • Traversal of binary tree

  • Use of queues

The traversal of the binary tree and the related concepts of the queue have been introduced before, and the forgotten friends will definitely double the effect after reviewing!

1Leetcode103 Maximum depth of binary tree

Given a binary tree, find its maximum depth.

The depth of the binary tree is the number of nodes on the longest path from the root node to the farthest leaf node.

Explanation: A  leaf node refers to a node without child nodes.





Example 1:

Given a binary tree [3,9,20,null,null,15,7],


    3

   / \

  9  20

    /  \

   15   7

Return its maximum depth 3.





Xiaolan hopes everyone will think about it for 1 minute

The effect is better!

0 1 Question analysis
  • Ideas 

Binary tree is divided into left subtree and right subtree, so the maximum depth can be understood as the larger value of the left and right subtrees +1 ( max(left,right)+1)). Under this statement, the tree’s Most of the recursive implementation will be much more concise, but in order to consolidate how to use data structures such as stacks or queues to implement iteratively, Xiaolan hopes to understand.


  • To access from the root node, first put the root node in the queue and record the node depth.

cebf33c3e72cb00af295aa6f7184681b.png

  • Recycle elements from the queue. Take out element A, A has left and right nodes B and C, and put it into the queue, and the depth is +1.

1ffa7073b28080ce2a5d4bd438281859.png

  • Follow step 2, take element B from the queue, and enqueue its left and right nodes. The depth at this time is 3.

4a2932182351c274e069dfebbbccfa21.png




02 code implementation

1c++ version

73725688e1716fc98ea098f8cf032d40.jpeg

2python version

0dd4d9bc38c9793e448dacd01d35659c.jpeg

3java version

bf51f4f97b22a8dcba711f0afe3a597b.jpeg




Warm man told

If you make a little progress with Xiaolan every day, your life will be better!

Enter algorithm, interview learning group, and grow together!

Pay attention to the bottom and reply "Enter the group" to enter our team.

0eb6913929c366bac21738af11861b00.jpeg

Pay attention to internal resources!


Guess you like

Origin blog.51cto.com/14984904/2545487