Leetcode(W3):104. Maximum Depth of Binary Tree

前言:又虚度了个周某,被自己浪哭了。


1. Maximum Depth of Binary Tree

介绍:

Given a binary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

题意:

即求二叉树的深度

思路:

因为结构体里有左右两个节点的指针,设定一个保存结果的值,初始化为1,每往左或者右扫一个节点,这个值+1。然后用BFS或者DFS从根节点不断遍历下去即可。

操作:

BFS和DFS的代码基本一样,只不过BFS用队列,DFS用栈

2. 代码

非递归BFS:
class Solution {
public:
    int bfs(struct TreeNode* root) {
        int result = 1;
        queue<pair<TreeNode*, int>> q;
        q.push({root, 1});
        while (!q.empty()) {
            TreeNode *cur = q.front().first;
            int dep = q.front().second;
            q.pop();
            if (dep > result)  result = dep;
            if (cur->left)  q.push({cur->left, dep+1});
            if (cur->right) q.push({cur->right, dep+1});
        }
        return result;
    }
    int maxDepth(TreeNode* root) {
        if (root) {
            return bfs(root);
        }
        return 0;
    }
};
非递归DFS:
class Solution {
public:
    int dfs(struct TreeNode* root) {
        int result = 1;
        stack<pair<TreeNode*, int>> s;
        s.push({root, 1});
        while (!s.empty()) {
            TreeNode *cur = s.top().first;
            int dep = s.top().second;
            s.pop();
            if (dep > result)  result = dep;
            if (cur->left)  s.push({cur->left, dep+1});
            if (cur->right) s.push({cur->right, dep+1});
        }
        return result;
    }
    int maxDepth(TreeNode* root) {
        if (root) {
            return dfs(root);
        }
        return 0;
    }
};

3.递归解

作为一道水题。。。DFS递归版的代码是真滴简略:

class Solution {
public:
    int maxDepth(TreeNode* root) {
        if (root) return 1+ max(maxDepth(root->left), maxDepth(root->right));
        return 0;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值