mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2026-02-02 18:39:09 +08:00
Update
This commit is contained in:
@@ -42,14 +42,14 @@
|
||||
1. 确定递归函数的参数和返回值:参数就是传入树的根节点,返回就返回这棵树的深度,所以返回值为int类型。
|
||||
|
||||
代码如下:
|
||||
```c++
|
||||
```CPP
|
||||
int getdepth(treenode* node)
|
||||
```
|
||||
|
||||
2. 确定终止条件:如果为空节点的话,就返回0,表示高度为0。
|
||||
|
||||
代码如下:
|
||||
```c++
|
||||
```CPP
|
||||
if (node == null) return 0;
|
||||
```
|
||||
|
||||
@@ -57,7 +57,7 @@ if (node == null) return 0;
|
||||
|
||||
代码如下:
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
int leftdepth = getdepth(node->left); // 左
|
||||
int rightdepth = getdepth(node->right); // 右
|
||||
int depth = 1 + max(leftdepth, rightdepth); // 中
|
||||
@@ -66,7 +66,7 @@ return depth;
|
||||
|
||||
所以整体c++代码如下:
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int getdepth(treenode* node) {
|
||||
@@ -83,7 +83,7 @@ public:
|
||||
```
|
||||
|
||||
代码精简之后c++代码如下:
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int maxdepth(treenode* root) {
|
||||
@@ -99,7 +99,7 @@ public:
|
||||
|
||||
本题当然也可以使用前序,代码如下:(**充分表现出求深度回溯的过程**)
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int result;
|
||||
@@ -122,7 +122,7 @@ public:
|
||||
}
|
||||
int maxdepth(treenode* root) {
|
||||
result = 0;
|
||||
if (root == 0) return result;
|
||||
if (root == NULL) return result;
|
||||
getdepth(root, 1);
|
||||
return result;
|
||||
}
|
||||
@@ -133,7 +133,7 @@ public:
|
||||
|
||||
注意以上代码是为了把细节体现出来,简化一下代码如下:
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int result;
|
||||
@@ -171,7 +171,7 @@ public:
|
||||
|
||||
c++代码如下:
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int maxdepth(treenode* root) {
|
||||
@@ -218,7 +218,7 @@ public:
|
||||
|
||||
c++代码:
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int maxdepth(node* root) {
|
||||
@@ -235,7 +235,7 @@ public:
|
||||
|
||||
依然是层序遍历,代码如下:
|
||||
|
||||
```c++
|
||||
```CPP
|
||||
class solution {
|
||||
public:
|
||||
int maxdepth(node* root) {
|
||||
|
||||
Reference in New Issue
Block a user