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

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]二叉树转换线索二叉树

上一篇:手把手教你appium_mac上环境搭建


下一篇:机器学习中的数学(5)-强大的矩阵奇异值分解(SVD)及其应用