随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-05-12 06:27

题目链接

原题:

Find the max height of a binary tree.

题目:计算二叉树的最大高度。

解法:最大高度?高度不就是最深的叶子节点到根节点的路径长度吗?我就当是高度吧,递归解决。

代码:

复制代码
 1 // http://www.careercup.com/question?id=5672369481842688
 2 #include <algorithm>
 3 #include <iostream>
 4 #include <sstream>
 5 #include <string>
 6 using namespace std;
 7 
 8 struct TreeNode {
 9     int val;
10     TreeNode *left;
11     TreeNode *right;
12     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
13 };
14 
15 int height(TreeNode *root)
16 {
17     return root ? 1 + max(height(root->left), height(root->right)) : 0;
18 }
19 
20 void constructBinaryTree(TreeNode *&root)
21 {
22     static int val;
23     static string str;
24     static stringstream sio;
25     
26     if (cin >> str && str != "#") {
27         sio << str;
28         sio >> val;
29         root = new TreeNode(val);
30         constructBinaryTree(root->left);
31         constructBinaryTree(root->right);
32     } else {
33         root = nullptr;
34     }
35 }
36 
37 void deleteTree(TreeNode *&root)
38 {
39     if (root == nullptr) {
40         return;
41     } else {
42         deleteTree(root->left);
43         deleteTree(root->right);
44         delete root;
45         root = nullptr;
46     }
47 }
48 
49 int main()
50 {
51     TreeNode *root;
52     
53     while (true) {
54         constructBinaryTree(root);
55         if (root == nullptr) {
56             break;
57         }
58         cout << height(root) << endl;
59         deleteTree(root);
60     }
61     
62     return 0;
63 }
复制代码

 

 posted on   zhuli19901106  阅读(175)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示