码迷,mamicode.com
首页 > 其他好文 > 详细

Recover Binary Search Tree

时间:2015-03-30 11:24:41      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:中序遍历   二叉树   

Two elements of a binary search tree (BST) are swapped by mistake.

Recover the tree without changing its structure.

#include<iostream>
#include<vector>
#include<stack>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};


void recoverTree(TreeNode *root) {

	TreeNode* pre_node = NULL;
	stack<TreeNode*>StackNode;
	TreeNode*cur_node = root;
	TreeNode*misnode1 = NULL;
	TreeNode*misnode2 = NULL;
	while (1)
	{
		while (cur_node)
		{
			StackNode.push(cur_node);
			cur_node = cur_node->left;
		}
		if (StackNode.empty())  
			break; 
		cur_node = StackNode.top();
		StackNode.pop();
		if (pre_node!=NULL&&pre_node->val>cur_node->val)
		{
			if (!misnode1){
				misnode1 = pre_node;
				misnode2 = cur_node;
			}
			else
				misnode2 = cur_node;
		}
		pre_node = cur_node;
		cur_node = cur_node->right;
	}
    if (misnode1&&misnode2)
		swap(misnode1->val,misnode2->val);
}

Recover Binary Search Tree

标签:中序遍历   二叉树   

原文地址:http://blog.csdn.net/li_chihang/article/details/44747221

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!