程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> leetcode - Recover Binary Search Tree

leetcode - Recover Binary Search Tree

編輯:C++入門知識

leetcode - Recover Binary Search Tree


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

Recover the tree without changing its structure.

Note:
A solution using O(n) space is pretty straight forward. Could you devise a constant space solution?

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
struct TreeNode
{
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
    void recoverTree(TreeNode *root) {
		 pre = n1 = n2 = NULL;
		 dfs(root);
		 n1->val ^= n2->val;
		 n2->val ^= n1->val;
		 n1->val ^= n2->val;
    }
private:
	TreeNode *pre,*n1,*n2;
	void dfs(TreeNode *root)
	{
		if(root == NULL) return;
		dfs(root->left);
		if(pre != NULL &&pre->val > root->val)
		{
			n1 = root;
			if(n2 == NULL) n2 = pre;
		}
		pre = root;
		dfs(root->right);
	}
};


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved