面试题27 二叉搜索树转换为双向链表

中序遍历的应用。

struct Node
{
	int val;
	Node *left;
	Node *right;
	Node(int a): val(a), left(NULL), right(NULL){}
};

Node * Convert(Node *root){

	if(root == NULL) return NULL;
	Node *head, *pNode, *p;
	head = pNode = NULL;
	stack<Node*> mys;
	p = root;
	while(!mys.empty() || p != NULL){

		while(p != NULL){
			mys.push(p);
			p = p->left;
		}
		
		p = mys.top();mys.pop();
		
		if(pNode == NULL){
			head = p;
			pNode = p;
			pNode->left = NULL;
		}else{
			pNode->right = p;
			p->left = pNode;
		    pNode = p;
		}
		p = p->right;
	}
	pNode->right = NULL;
	return head;
}

  

posted @ 2013-09-15 15:27  冰点猎手  阅读(190)  评论(0编辑  收藏  举报