Merge pull request #963 from IcePigZDB/maxDepth

二叉树最大深度 null->NULL
This commit is contained in:
程序员Carl
2021-12-30 12:53:26 +08:00
committed by GitHub

View File

@ -48,7 +48,7 @@ int getdepth(treenode* node)
代码如下: 代码如下:
```CPP ```CPP
if (node == null) return 0; if (node == NULL) return 0;
``` ```
3. 确定单层递归的逻辑:先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 加1是因为算上当前中间节点就是目前节点为根节点的树的深度。 3. 确定单层递归的逻辑:先求它的左子树的深度,再求的右子树的深度,最后取左右深度最大的数值 再+1 加1是因为算上当前中间节点就是目前节点为根节点的树的深度。
@ -68,7 +68,7 @@ return depth;
class solution { class solution {
public: public:
int getdepth(treenode* node) { int getdepth(treenode* node) {
if (node == null) return 0; if (node == NULL) return 0;
int leftdepth = getdepth(node->left); // 左 int leftdepth = getdepth(node->left); // 左
int rightdepth = getdepth(node->right); // 右 int rightdepth = getdepth(node->right); // 右
int depth = 1 + max(leftdepth, rightdepth); // 中 int depth = 1 + max(leftdepth, rightdepth); // 中
@ -104,7 +104,7 @@ public:
void getdepth(treenode* node, int depth) { void getdepth(treenode* node, int depth) {
result = depth > result ? depth : result; // 中 result = depth > result ? depth : result; // 中
if (node->left == null && node->right == null) return ; if (node->left == NULL && node->right == NULL) return ;
if (node->left) { // 左 if (node->left) { // 左
depth++; // 深度+1 depth++; // 深度+1
@ -137,7 +137,7 @@ public:
int result; int result;
void getdepth(treenode* node, int depth) { void getdepth(treenode* node, int depth) {
result = depth > result ? depth : result; // 中 result = depth > result ? depth : result; // 中
if (node->left == null && node->right == null) return ; if (node->left == NULL && node->right == NULL) return ;
if (node->left) { // 左 if (node->left) { // 左
getdepth(node->left, depth + 1); getdepth(node->left, depth + 1);
} }
@ -173,7 +173,7 @@ c++代码如下:
class solution { class solution {
public: public:
int maxdepth(treenode* root) { int maxdepth(treenode* root) {
if (root == null) return 0; if (root == NULL) return 0;
int depth = 0; int depth = 0;
queue<treenode*> que; queue<treenode*> que;
que.push(root); que.push(root);
@ -238,7 +238,7 @@ class solution {
public: public:
int maxdepth(node* root) { int maxdepth(node* root) {
queue<node*> que; queue<node*> que;
if (root != null) que.push(root); if (root != NULL) que.push(root);
int depth = 0; int depth = 0;
while (!que.empty()) { while (!que.empty()) {
int size = que.size(); int size = que.size();