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 }
  • 相关阅读:
    Bundle类
    intent.putExtra()方法参数详解
    6级技巧(一)
    6级核心词汇
    安卓应用运营知识:VersionCode和VersionName
    关于HTML、XHTML、CSS、XML的区别
    SQL记录-Linux CentOS配置ORACLE 12c
    Spark记录-Scala多线程
    Spark记录-Scala异常与处理
    Spark记录-Scala类和对象
  • 原文地址:https://www.cnblogs.com/zhuli19901106/p/3610468.html
Copyright © 2011-2022 走看看