title: Daily practice (27): The depth of the binary tree
categories:[Swords offer]
tags:[Daily practice]
date: 2022/02/26
Daily practice (27): The depth of the binary tree
Enter the root node of a binary tree and find the depth of the tree. The nodes (including the root and leaf nodes) that pass through in sequence from the root node to the leaf node form a path of the tree, and the length of the longest path is the depth of the tree.
E.g:
Given a binary tree [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
Returns its maximum depth of 3.
hint:
Total number of nodes <= 10000
Source: LeetCode
Link: https://leetcode-cn.com/problems/er-cha-shu-de-shen-du-lcof
Method 1: Recursion
Subsequent traversal:
Follow the recursion trilogy to see how to write it.
1. Determine the parameters and return value of the recursive function: The parameter is the root node of the incoming tree, and the return value returns the depth of the tree, so the return value is of type int.
code show as below:
int getDepth(TreeNode* node)
2. Determine the termination condition: if it is an empty node, return 0, indicating that the height is 0.
code show as below:
if (node == NULL) return 0;
3. Determine the logic of single-level recursion: first find the depth of its left subtree, then find the depth of the right subtree, and finally take the value with the largest depth around and then +1 (add 1 because the current intermediate node is counted) is the depth of the tree whose current node is the root node.
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
//1简化前
int getDepth(TreeNode *root) {
if (root == NULL) {
return 0;
}
int leftDepth = getDepth(node->left); // 左
int rightDepth = getDepth(node->right); // 右
int depth = 1 + max(leftDepth, rightDepth); // 中
return depth;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
//2简化后
int maxDepth(TreeNode* root) {
return (root == NULL) ? 0 : 1 + max(maxDepth(root->left), maxDepth(root->right));
}
Method 2: Iterative method (BFS)
If you use the iterative method, it is most suitable to use the level-order traversal, because the maximum depth is the number of levels of the binary tree, which is very consistent with the level-order traversal method.
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int depth = 0;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
depth++;
int size = que.size();
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (node->left) {
que.push(node->left);
}
if (node->right) {
que.push(node->right);
}
}
}
return depth;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。