LC.104.二叉树的最大深度(DFS&BFS)

LC.104.二叉树的最大深度(DFS&BFS)

思路: d f s dfs b f s bfs

/**
 * 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;
    void dfs(TreeNode* root,int d){
          if(root==nullptr){
              ans=max(ans,d);
              return ;
          }
          dfs(root->left,d+1);
          dfs(root->right,d+1);
    }
    int maxDepth(TreeNode* root) {
        ans=0;
        dfs(root,0);
        return ans;
    }
};
/**
 * 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) {
       if(root==nullptr) return 0;
       return max(maxDepth(root->left),maxDepth(root->right))+1;
    }
};

b f s bfs 的代码就不写了,根先入队,主要是分层,每过一层深度加1,比较好写。

猜你喜欢

转载自blog.csdn.net/weixin_45750972/article/details/107632274
今日推荐