zoukankan      html  css  js  c++  java
  • 《Cracking the Coding Interview》——第4章:树和图——题目1

    2014-03-19 03:30

    题目:判断一个二叉树是否为平衡二叉树,即左右子树高度相差不超过1。

    解法:递归算高度并判断即可。

    代码:

     1 // 4.1 Implement an algorithm to check if a bianry tree is height-balanced.
     2 #include <algorithm>
     3 #include <cstdio>
     4 #include <unordered_map>
     5 using namespace std;
     6 
     7 struct TreeNode {
     8     int val;
     9     TreeNode *left;
    10     TreeNode *right;
    11     
    12     TreeNode(int _val = 0): val(_val), left(nullptr), right(nullptr) {};
    13 };
    14 
    15 void constructBinaryTree(TreeNode *&root)
    16 {
    17     int val;
    18     
    19     scanf("%d", &val);
    20     if (val <= 0) {
    21         root = nullptr;
    22     } else {
    23         root = new TreeNode(val);
    24 
    25         constructBinaryTree(root->left);
    26         constructBinaryTree(root->right);
    27     }
    28 }
    29 
    30 void clearBinaryTree(TreeNode *&root) {
    31     if (root == nullptr) {
    32         return;
    33     } else {
    34         clearBinaryTree(root->left);
    35         clearBinaryTree(root->right);
    36         delete root;
    37         root = nullptr;
    38     }
    39 }
    40 
    41 void calcHeights(TreeNode *root, unordered_map<TreeNode *, int> &heights)
    42 {
    43     if (root == nullptr) {
    44         heights[root] = 0;
    45     } else {
    46         calcHeights(root->left, heights);
    47         calcHeights(root->right, heights);
    48         heights[root] = max(heights[root->left], heights[root->right]) + 1;
    49     }
    50 }
    51 
    52 bool isBalanced(TreeNode *root, unordered_map<TreeNode *, int> &heights)
    53 {
    54     if (root == nullptr) {
    55         return true;
    56     } else {
    57         return abs(heights[root->left] - heights[root->right]) <= 1;
    58     }
    59 }
    60 
    61 int main()
    62 {
    63     TreeNode *root;
    64     unordered_map<TreeNode *, int> heights;
    65     
    66     while (true) {
    67         constructBinaryTree(root);
    68         if (root == nullptr) {
    69             break;
    70         }
    71         
    72         calcHeights(root, heights);
    73         if (isBalanced(root, heights)) {
    74             printf("Yes
    ");
    75         } else {
    76             printf("No
    ");
    77         }
    78         heights.clear();
    79         clearBinaryTree(root);
    80     }
    81     
    82     return 0;
    83 }
  • 相关阅读:
    Mybatis框架学习笔记一(基于注解的配置)
    HDU 1686 Oulipo (KMP模板题)
    监控Windows性能指标
    Locust设置检查点
    《TCP/IP网络编程》读书笔记
    基于单向链表的队列的实现
    windows下基于异步通知IO模型的回声服务器和客户端的实现
    c语言实现迭代器iterator
    c语言hash表的实现
    c语言双向链表的实现
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3610468.html
Copyright © 2011-2022 走看看