
深度优先搜索代码:
/**
* 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 maxDepth(TreeNode* root) {
int depth=0,high=0;
dfs(root,depth,high);
return depth;
}
void dfs(TreeNode* root,int &depth,int high){
if(root==NULL) return;
high++;
if(high>depth) depth=high;
dfs(root->left,depth,high);
dfs(root->right,depth,high);
high--;
}
};
精简版:
/**
* 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 maxDepth(TreeNode* root) {
return root==NULL? 0: 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
来源:https://www.cnblogs.com/joelwang/p/10692423.html