Leedcode1-求树的最小高度
发布日期:2025-04-04 18:29:35 浏览次数:13 分类:精选文章

本文共 1969 字,大约阅读时间需要 6 分钟。

#include 
#include
#include
using namespace std; // 处理二叉树深度问题 // 情况分析:空树;没有子树;只有左/右子树;有两子树 struct BinaryNode { BinaryNode *left; BinaryNode *right; int data; }; struct BinaryTree { BinaryNode *head; }; // 后序遍历实现深度计算 int getDepth(BinaryNode *node) { if (node == NULL) { return 0; } int left_depth = getDepth(node->left); int right_depth = getDepth(node->right); if (left_depth && right_depth) { return min(left_depth, right_depth) + 1; } else { return max(left_depth, right_depth) + 1; } } // 层次遍历实现深度计算 int getDepth2(BinaryNode *root) { if (root == NULL) { return 0; } queue
q; q.push(root); int depth = 0; while (!q.empty()) { queue
qt; depth++; while (!q.empty()) { BinaryNode *temp = q.front(); q.pop(); if (!temp->left && !temp->right) { return depth; } if (temp->left) { qt.push(temp->left); } if (temp->right) { qt.push(temp->right); } } q = qt; } return depth; } int main() { // 构建示例二叉树 BinaryTree btree; BinaryNode node1 = { NULL, NULL, 7 }; BinaryNode node2 = { NULL, NULL, 9 }; BinaryNode node3 = { NULL, NULL, 8 }; BinaryNode node4 = { NULL, NULL, 4 }; BinaryNode node5 = { NULL, NULL, 2 }; BinaryNode node6 = { NULL, NULL, 5 }; BinaryNode node7 = { NULL, NULL, 10 }; btree.head = &node1; node1.left = &node3; node1.right = &node2; node2.right = &node7; node3.left = &node4; node4.left = &node5; node4.right = &node6; // 计算树的深度 int height = getDepth2(&node1); cout << height << endl; }

运行结果:

上一篇:Leedcode10-linked-list-cycle-ii
下一篇:Lebesgue积分的收敛定理

发表评论

最新留言

第一次来,支持一个
[***.219.124.196]2025年04月30日 03时12分40秒