c++ - 二叉树和特殊节点打印

标签 c++ tree binary-tree

我有这样一棵二进制表示的树;

                 1
                /
               2
                \
                 3
                / \
               6   4
                \   \
                 7   5
                    /
                   8
                  /
                 9
                  \
                   10
                     \
                      11

但实际上这不是二叉树而是像

     1
  / | | \
 2  3 4 5
    /\  |
    6 7 8
       /| \
      9 10 11

你能帮我打印出类似的东西吗( children 以相反的顺序打印出来)

1 : 5 4 3 2
5 : 8
3 : 7 6
8 : 11 10 9

我的 TNode 类看起来像。

class TNode {
public:
    unsigned long int data;
    TNode * left;///first child
    TNode * right;/// sibling
    TNode * parent;/// parent

    TNode(unsigned long int d = 0, TNode * p = NULL, TNode * n = NULL)///konstruktors
    {
        left = NULL;
        right = NULL;
        parent = p;
        data = d;
    }
};

这需要堆栈实现吗?

最佳答案

这种方法怎么样: 按预定顺序遍历树(访问每个节点)。对于每个节点(当到达它时)检查它是否有左 child 。如果是这样(表示原始树中具有子元素的节点)用':'打印节点数据并获取其子树并递归地跟随所有右儿子(代表所有 sibling ),然后打印每个右儿子数据(你有它以相反的顺序。 在代码中:

void print_siblings() {
    if (this->right != NULL) {
        this->right->print_siblings();
    }
    cout << data << ", ";
}

void traverse(void) {
    if (this->left != NULL) {
        cout << data << ":";
        this->left->print_siblings();
        cout << endl;
        this->left->traverse();
    }

    if (this->right != NULL) {
        this->right->traverse();
    }
}

编辑:这是一个中序遍历:

void traverse_inorder(void) {
    if (this->left != NULL) {
        this->left->traverse_inorder();
        cout << data << ":";
        this->left->print_siblings();
        cout << endl;
    }

    if (this->right != NULL) {
        this->right->traverse_inorder();
    }
}

预购的输出将是:

1:5, 4, 3, 2,
3:7, 6,
5:8,
8:11, 10, 9,

inorder 的输出为:

3:7, 6,
8:11, 10, 9,
5:8,
1:5, 4, 3, 2,

Edit2:为了完整起见,后序遍历也是如此:-)

void traverse_postorder(void) {
    if (this->left != NULL) {
        this->left->traverse_postorder();
    }

    if (this->right != NULL) {
        this->right->traverse_postorder();
    }
    if (this->left != NULL) {
        cout << data << ":";
        this->left->print_siblings();
        cout << endl;
    }

}

及其输出:

8:11, 10, 9,
5:8,
3:7, 6,
1:5, 4, 3, 2,

关于c++ - 二叉树和特殊节点打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19633808/

相关文章:

c++ - 在 C++11 中哪些临时对象不能用 `someType()` 初始化?

c++ - 如何在 Eclipse IDE 上显示语法着色和范围界定?

tree - 如何在 TreePanel 中插入新记录(模型)?

algorithm - 动态规划 - 最佳断点

algorithm - 寻找二叉树最小值的时间复杂度

c++ - 计算两个已知大小和位置的物体之间的碰撞

c++ - ffmpeg AVFrame 中的 "opaque"指针

c - 如何修改我用 C 编写的树遍历程序,使其不依赖于递归?

c++ - 我不明白 find 函数在 C++ 中是如何工作的

c++ - 查找二叉树的高度