4ms Java Solution


  • 5
    P
    public class Solution {
        
         TreeNode first = null, second = null, pre = null;
        public void recoverTree(TreeNode root) {
            if(root==null)return;
            dfs(root);
            if(first!=null&&second!=null){
                int temp = first.val;
                first.val = second.val;
                second.val = temp;
            }
            
        }
        public void  dfs(TreeNode root){
            if(root.left!=null)dfs(root.left);
            if(pre!=null&&pre.val>root.val)
                {
                    if(first==null) first = pre;
                    if(first!=null)second = root;
                }
            pre = root;
            if(root.right!=null)dfs(root.right);
        }
    }

Log in to reply
 

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