这题想了很久,看了网上答案,这段代码精髓在于findpos第一个pos是在他下一个node函数里才被发现的,因为第一个pos->val是变大了,所以p是pre,而第二个pos是在他自己本身的函数里被发现的,因为第二个pos->val是变小了,所以就是root。
1 /** 2 * Definition for binary tree 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void findpos(TreeNode *root, TreeNode * &pre, TreeNode * &p, TreeNode * &q) { 13 if (!root) return; 14 findpos(root->left, pre, p, q); 15 if (pre && pre->val > root->val) { 16 if (!p) p = pre; 17 q = root; 18 } 19 pre = root; 20 findpos(root->right, pre, p, q); 21 } 22 void recoverTree(TreeNode *root) { 23 // Start typing your C/C++ solution below 24 // DO NOT write int main() function 25 TreeNode *p, *q, *pre; 26 pre = p = q = NULL; 27 findpos(root, pre, p, q); 28 int tmp = p->val; 29 p->val = q->val; 30 q->val = tmp; 31 } 32 };
C#
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * public int val; 5 * public TreeNode left; 6 * public TreeNode right; 7 * public TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public void RecoverTree(TreeNode root) { 12 TreeNode p = null, q = null, pre = null; 13 findpos(root, ref pre, ref p, ref q); 14 int tmp = p.val; 15 p.val = q.val; 16 q.val = tmp; 17 } 18 public void findpos(TreeNode root, ref TreeNode pre, ref TreeNode p, ref TreeNode q) { 19 if (root == null) return; 20 findpos(root.left, ref pre, ref p, ref q); 21 if (pre != null && pre.val > root.val) { 22 if (p == null) p = pre; 23 q = root; 24 } 25 pre = root; 26 findpos(root.right, ref pre, ref p, ref q); 27 } 28 }