zoukankan      html  css  js  c++  java
  • 左神算法书籍《程序员代码面试指南》——2_12将搜索二叉树转换成双向链表【★★】

    【题目】
    二叉树可以用常规的三种遍历结果来描述其结构,但是不够直观,尤其是二叉树中有重复值的时候,仅通过三种遍历的结果来构造二叉树的真实结构更是难上加难,有时则根本不可能。给定一棵二叉树的头节点head,已知二叉树节点值的类型为32位整型,请实现一个打印二叉树的函数,可以直观地展示树的形状,也便于画出真实的结构。

     1 class PrintTree
     2 {
     3 public:
     4     void Print(Node* root)
     5     {
     6         cout << "The shape of tree is: " << endl;
     7         cout << "=============================================================" << endl;
     8         PrintShape(root, 0, "H", 17);
     9         cout << "=============================================================" << endl;
    10     }
    11     void PrintShape(Node* root, int h, string c, int len)
    12     {
    13         if (root)
    14         {
    15             PrintShape(root->rchild, h + 1, "v", len);
    16             string val;
    17             stringstream ss;
    18             ss << root->val;
    19             ss >> val;
    20             val = c + val + c;
    21             int lenM = val.length();
    22             int lenL = (len - lenM) / 2;
    23             int lenR = len - lenM - lenL;
    24             val = getSpace(lenL) + val + getSpace(lenR);
    25             cout << getSpace(h*len) + val << endl;
    26             PrintShape(root->lchild, h + 1, "^", len);
    27         }
    28 
    29     }
    30     string getSpace(int num)
    31     {
    32         string space = " ";
    33         for (int i = 0; i < num; ++i)
    34             space.append(" ");
    35         return space;
    36     }
    37 };
  • 相关阅读:
    html5+css3中的background: -moz-linear-gradient 用法 (转载)
    CentOS 安装Apache服务
    Linux 笔记
    CURL 笔记
    Spring Application Context文件没有提示功能解决方法
    LeetCode 389. Find the Difference
    LeetCode 104. Maximum Depth of Binary Tree
    LeetCode 520. Detect Capital
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 136. Single Number
  • 原文地址:https://www.cnblogs.com/zzw1024/p/11450461.html
Copyright © 2011-2022 走看看