力扣-104-二叉树的最大深度

传送门

题目分析:

方法一:递归

求解根节点的最大深度,可以转化为根节点的深度$1$,加上左子树和右子树的最大深度中较大的那一个。通过分析,这明显是一个递归问题,用递归求解代码也比较简单。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

#include <algorithm>
using namespace std;

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root == NULL) return 0;
        return max(maxDepth(root->left), maxDepth(root->right)) + 1;
    }
};

 

方法二:$bfs$

求解树的最大深度,实际上可以通过bfs进行层次遍历,然后每遍历一层,$result$加一,$bfs$实现二叉树的层序遍历同上题。

/*二叉树求树的最大深度使用bfs*/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <queue>
#include <vector>
using namespace std;

class Solution {
public:
    int maxDepth(TreeNode* root) {
        int result = 0;
        queue<TreeNode*> tree;
        if (root!= NULL) tree.push(root);
        while(!tree.empty()){
            int num = tree.size();
            for(int i = 0; i < num; i++){
                TreeNode* node = tree.front();
                tree.pop();
                if(node->left != NULL) tree.push(node->left);
                if(node->right != NULL) tree.push(node->right);                
            }
            result += 1;
        }
        return result;
    }
};

 

posted @ 2020-08-02 19:42  Peterxiazhen  阅读(166)  评论(0编辑  收藏  举报