题意:

image.png

解题思路:

  1. 思路:
  2. 1. 中序遍历,产生的序列是严格递增的;
  3. 2. 递归找到两个数字,如果通过中序遍历得到的顺序为递减,说明前面的数字比后面的数字大,违背了中序遍历的顺序;
  4. 3. 记录前后两个递减节点,最后进行交换;

PHP代码实现:

  1. /**
  2. * Definition for a binary tree node.
  3. * class TreeNode {
  4. * public $val = null;
  5. * public $left = null;
  6. * public $right = null;
  7. * function __construct($val = 0, $left = null, $right = null) {
  8. * $this->val = $val;
  9. * $this->left = $left;
  10. * $this->right = $right;
  11. * }
  12. * }
  13. */
  14. class Solution {
  15. /**
  16. * @param TreeNode $root
  17. * @return NULL
  18. */
  19. function recoverTree($root) {
  20. if ($root == null) return;
  21. $this->helper($root);
  22. $temp = $this->firstNode->val;
  23. $this->firstNode->val = $this->secondNode->val;
  24. $this->secondNode->val = $temp;
  25. }
  26. public $firstNode;
  27. public $secondNode;
  28. public $pre;
  29. function helper($root) {
  30. if ($root == null) return;
  31. $this->helper($root->left);
  32. if ($this->pre == null) $this->pre = $root;
  33. else {
  34. if ($this->pre->val > $root->val) {
  35. if ($this->firstNode == null) {
  36. $this->firstNode = $this->pre;
  37. }
  38. $this->secondNode = $root;
  39. }
  40. $this->pre = $root;
  41. }
  42. $this->helper($root->right);
  43. }
  44. }

GO代码实现:

  1. var first, second, pre *TreeNode
  2. func recoverTree(root *TreeNode) {
  3. first, second, pre = nil, nil, nil
  4. helper(root)
  5. first.Val, second.Val = second.Val, first.Val
  6. }
  7. func helper(root *TreeNode) {
  8. if root == nil {
  9. return
  10. }
  11. helper(root.Left)
  12. if pre != nil && pre.Val > root.Val {
  13. second = root
  14. if first == nil {
  15. first = pre
  16. } else {
  17. return
  18. }
  19. }
  20. pre = root
  21. helper(root.Right)
  22. }