Share my java solution using the same notion with problem 94 and 98


  • 0
    P

    We can solve this kind of problem using the same notion and structure with the problem Binary Tree In-order Traversal and Validate Binary Search Tree. Any comment is welcome! :)
    '''
    public class Solution {

    public void recoverTree(TreeNode root) {
        if(root==null){
            return;
        }
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode pre = null;
        TreeNode firstNode = null;
        TreeNode secondNode = null;
        while(root!=null||!stack.isEmpty()){
            while(root!=null){
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();
            if(pre!=null&&root.val<=pre.val){
                if(firstNode==null){
                    firstNode = pre;
                }
                if(firstNode!=null){
                    secondNode = root;
                }
            }
            pre = root;
            root = root.right;
        }
        int temp = firstNode.val;
        firstNode.val = secondNode.val;
        secondNode.val = temp;
        return;
    }
    

    }
    '''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.