1.递归遍历时通过“参数传递”自顶向下传递信息
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int ans = 0;//全局变量,在各级函数间共享信息
int treeDepth(TreeNode* root) {
dfs(root, 1);
return ans;
}
void dfs(TreeNode* root, int depth){
if(!root) return;
ans = max(ans, depth);
dfs(root->left, depth + 1);
dfs(root->right, depth + 1);
}
};
2.递归遍历时,通过“函数返回值”自底向上传递信息
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int ans = 0;
int treeDepth(TreeNode* root) {
return dfs(root);
}
int dfs(TreeNode* root){
if(!root) return 0;
int l = dfs(root->left);
int r = dfs(root->right);
return max(l, r) + 1;
}
};