您的位置:首页 > 职场人生

Careercup - Microsoft面试题 - 5672369481842688

2014-05-12 06:30 274 查看
2014-05-12 06:27

题目链接

原题:

Find the max height of a binary tree.


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

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

代码:

// http://www.careercup.com/question?id=5672369481842688 #include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;

struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
};

int height(TreeNode *root)
{
return root ? 1 + max(height(root->left), height(root->right)) : 0;
}

void constructBinaryTree(TreeNode *&root)
{
static int val;
static string str;
static stringstream sio;

if (cin >> str && str != "#") {
sio << str;
sio >> val;
root = new TreeNode(val);
constructBinaryTree(root->left);
constructBinaryTree(root->right);
} else {
root = nullptr;
}
}

void deleteTree(TreeNode *&root)
{
if (root == nullptr) {
return;
} else {
deleteTree(root->left);
deleteTree(root->right);
delete root;
root = nullptr;
}
}

int main()
{
TreeNode *root;

while (true) {
constructBinaryTree(root);
if (root == nullptr) {
break;
}
cout << height(root) << endl;
deleteTree(root);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: