11 lines C++ in-order traversal

  • 0
    class Solution {
        void recoverTree(TreeNode* root) {
            TreeNode* pre = NULL, *one = NULL, *two = NULL;
            DFS(root, pre, one, two);
            swap(one->val, two->val);
        void DFS(TreeNode* cur, TreeNode* &pre, TreeNode* &one, TreeNode* &two){
            if(!cur) return;
            DFS(cur->left, pre, one, two);
            if(pre && cur->val < pre->val){
                if(!one) one = pre;
                two = cur;
            pre = cur;
            DFS(cur->right, pre, one, two);

Log in to reply

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