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; }
相关文章推荐
- Careercup - Microsoft面试题 - 5799446021406720
- Careercup - Microsoft面试题 - 5752271719628800
- Careercup - Microsoft面试题 - 24313662
- Careercup - Microsoft面试题 - 24308662
- Careercup - Microsoft面试题 - 5943729928011776
- Careercup - Microsoft面试题 - 23123665
- Careercup - Microsoft面试题 - 6366101810184192
- Careercup - Microsoft面试题 - 5120588943196160
- Careercup - Microsoft面试题 - 5673934611546112
- Careercup - Microsoft面试题 - 5684901156225024
- Careercup - Microsoft面试题 - 5204967652589568
- Careercup - Microsoft面试题 - 6337018766295040
- Careercup - Microsoft面试题 - 6543214668414976
- Careercup - Microsoft面试题 - 5700293077499904
- Careercup - Microsoft面试题 - 5680049562845184
- Careercup - Microsoft面试题 - 5428361417457664
- Careercup - Microsoft面试题 - 5188169901277184
- Careercup - Microsoft面试题 - 4840369632051200
- Careercup - Microsoft面试题 - 6282862240202752
- Careercup - Microsoft面试题 - 5485521224597504