美文网首页
剑指offer 59- 二叉树的深度

剑指offer 59- 二叉树的深度

作者: 顾子豪 | 来源:发表于2021-06-04 02:25 被阅读0次

输入一棵二叉树的根结点,求该树的深度。

从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

样例

输入:二叉树[8, 12, 2, null, null, 6, 4, null, null, null, null]如下图所示:
    8
   / \
  12  2
     / \
    6   4

输出:3

分析:
算法一:递归实现
时间复杂度:O(N) N为二叉树的结点个数

/**
 * 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 treeDepth(TreeNode* root) {
        if(!root) return 0;
        return 1 + max(treeDepth(root->left), treeDepth(root->right));
    }

};

算法二:BFS,队列实现
时间复杂度:O(N) N为二叉树的结点个数

/**
 * 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 treeDepth(TreeNode* root) {
        int res = 0;
        queue<TreeNode*> q;
        if(!root) return 0;
        q.push(root);
        while(q.size()) {
            int n = q.size();
            //遍历一层
            for(int i = 0; i<n; i++) {
                auto x = q.front();
                q.pop();
                if(x->left) q.push(x->left);
                if(x->right) q.push(x->right);
            }
            //一层遍历完后,计数加一
            res++;
        }
        
        return res;
    }

};

算法三:DFS
时间复杂度:O(N) N为二叉树的结点个数

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

};

相关文章

网友评论

      本文标题:剑指offer 59- 二叉树的深度

      本文链接:https://www.haomeiwen.com/subject/mitojltx.html