Cover image for leetcode热题100 P543 二叉树的直径

leetcode热题100 P543 二叉树的直径

字数 382
阅读
访客

时间轴

时间轴

2026-03-14

init

后序遍历,二叉树的深度

题目:

非递归写法:

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
struct TreeNode {        int val;        TreeNode *left;        TreeNode *right;        TreeNode()                : val(0)                , left(nullptr)                , right(nullptr)        {        }        TreeNode(int x)                : val(x)                , left(nullptr)                , right(nullptr)        {        }        TreeNode(int x, TreeNode *left, TreeNode *right)                : val(x)                , left(left)                , right(right)        {        }};#include <stack>#include <unordered_map>using std::stack;using std::unordered_map;class Solution {    public:        int diameterOfBinaryTree(TreeNode *root)        {                // 每个节点左子树深度+右子树深度得最大值                stack<TreeNode *> stk;                unordered_map<TreeNode *, int> node_depth;                TreeNode *last = nullptr, *p = root;                int res = 0, left_depth, right_depth;                while (p || !stk.empty()) {                        if (p) {                                stk.push(p);                                p = p->left;                        } else {                                p = stk.top();                                if (p->right && last != p->right) {                                        p = p->right;                                } else {                                        // visit p                                        left_depth = (p->left) ? node_depth[p->left] : 0;                                        right_depth = (p->right) ? node_depth[p->right] : 0;                                        node_depth[p] = std::max(left_depth, right_depth) + 1;                                        res = std::max(res, left_depth + right_depth);                                        stk.pop();                                        last = p;                                        p = nullptr;                                }                        }                }                return res;        }};

递归写法:实际上是求每个节点的左子树和右子树深度之和的最大值

123456789101112131415161718192021
class Solution {        int ans;        int depth(TreeNode *rt)        {                if (rt == NULL) {                        return 0; // 访问到空节点了,返回0                }                int L = depth(rt->left); // 左儿子为根的子树的深度                int R = depth(rt->right); // 右儿子为根的子树的深度                ans = max(ans, L + R + 1); // 计算d_node即L+R+1 并更新ans                return max(L, R) + 1; // 返回该节点为根的子树的深度        }    public:        int diameterOfBinaryTree(TreeNode *root)        {                ans = 1;                depth(root);                return ans - 1;        }};
评论加载中…