首页 > 其他 > 详细

[itint5]二叉树转换线索二叉树

时间:2014-01-21 23:21:08      阅读:343      评论:0      收藏:0      [点我收藏+]

http://www.itint5.com/oj/#27

用了基于stack的中序遍历,记录一下last,就很简单了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stack>
 
/*树结点的定义(请不要在代码中定义该结构)
struct TreeNode {
  TreeNode *left, *right;
  bool isLeftThread, isRightThread;
}*/
void convertToThreadedTree(TreeNode *root) {
    stack<TreeNode*> stak;
    TreeNode *n = root;
    TreeNode *last = NULL;
    while (n != NULL || !stak.empty()) {
        if (n != NULL) {
            stak.push(n);
            n = n->left;
        } else {
            n = stak.top();
            stak.pop();
            // visit n
            if (last != NULL) {
                if (last->right == NULL) {
                    last->right = n;
                    last->isRightThread = true;
                }
                if (n->left == NULL) {
                    n->left = last;
                    n->isLeftThread = true;
                }
            }
            last = n;
            n = n->right;
        }
    }
}

  

[itint5]二叉树转换线索二叉树

原文:http://www.cnblogs.com/lautsie/p/3528890.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!