美文网首页
[LeetCode 99] Recover Binary Sea

[LeetCode 99] Recover Binary Sea

作者: 灰睛眼蓝 | 来源:发表于2019-06-04 13:47 被阅读0次

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

    Recover the tree without changing its structure.

    Example 1:

    Input: [1,3,null,null,2]
    
       1
      /
     3
      \
       2
    
    Output: [3,1,null,null,2]
    
       3
      /
     1
      \
       2
    

    Example 2:

    Input: [3,1,4,null,null,2]
    
      3
     / \
    1   4
       /
      2
    
    Output: [2,1,4,null,null,3]
    
      2
     / \
    1   4
       /
      3
    

    Follow up:

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

    Solution: InOrder Traverse

    1. 用中序遍历 (正常时遍历的值为升序)
    2. 但是有2个节点出现的错误,就打破了升序。
      • 那么只要找到第一个 current.val < prev.val,那么prev就是第一个出错的节点
      • 然后再找到第二个 current.val < prev.val,那么prev就是第二个出错的节点
    3. 交换即可
    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    class Solution {
        public void recoverTree(TreeNode root) {
            TreeNode first = null;
            TreeNode second = null;
            TreeNode prev = null;
            
            Stack<TreeNode> tracker = new Stack<> ();
            TreeNode current = root;
            
            while (!tracker.isEmpty () || current != null) {
                if (current != null) {
                    tracker.push (current);
                    current = current.left;
                } else {
                    current = tracker.pop ();
                    
                    // find the two nodes which have been swapped incorrectly
                    // cannot use if else here, for example [3,1,4,null,null,2], which in-order is 1 3 2 4, prev: 3, current 2. 
                    // the first and second nodes are found at the same time. so we cannot use if else.
                    if (prev != null && current.val < prev.val) {
                        if (first == null)
                            first = prev;
                        second = current;
                    }
                    
                    prev = current;
                    current = current.right;
                }
            }
            
            int temp = first.val;
            first.val = second.val;
            second.val = temp;
            
        }
    }
    

    相关文章

      网友评论

          本文标题:[LeetCode 99] Recover Binary Sea

          本文链接:https://www.haomeiwen.com/subject/kfmvbqtx.html