zoukankan      html  css  js  c++  java
  • Careercup

    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 }
  • 相关阅读:
    vue分享二维码
    Linux的软件安装
    linux命令操作
    禅道的使用方法
    测试管理工具的安装和介绍
    测试Bug
    软件缺陷和软件缺陷的种类
    测试计划和测试用例
    双肩包,椅子,电梯的测试用例
    软件生命周期的模型
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3722685.html
Copyright © 2011-2022 走看看