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

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

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

#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;

        }

    }

}

  

你可能感兴趣的:(二叉树)