题解 | #找到搜索二叉树中两个错误的节点#

找到搜索二叉树中两个错误的节点

https://www.nowcoder.com/practice/4582efa5ffe949cc80c136eeb78795d6

首先,搜索二叉树,中序遍历有序

通过观察示例可以发现,错误有两种情况:子节点之间互换,子节点和直接父节点之间互换。

第一种情况,直接找到 找到两个比其后元素大的,第一个取大的,第二个取小的

关于第二种情况,注意此时中序遍历后数据大小关系是:大小大或者小大小,这样的话,补充result[0]为当前节点即可

所以为了兼容,直接取result[0]为当前,result[1]为较大的前驱。

import java.util.*;

/*
 * public class TreeNode {
 *   int val = 0;
 *   TreeNode left = null;
 *   TreeNode right = null;
 * }
 */

public class Solution {
    /**
     * 
     * @param root TreeNode类 the root
     * @return int整型一维数组
     */
    private int[] result;
    private TreeNode pre = null; 
    public int[] findError (TreeNode root) {
        // 
        // 结束条件:全部找到或者到达null,返回
        // 单层逻辑:
        if (root == null) {
            return new int[0];
        }
        result = new int[2];
        result[0] = 0;
        result[1] = 0;
        findTwoError(root);
        // Arrays.sort(result);
        return result;
    }

    private void findTwoError(TreeNode root) {
        if (root == null) {
            return;
        }
        findTwoError(root.left);
        if (pre != null && pre.val > root.val) {
            if (result[1] > 0) {
                result[0] = root.val;
            } else {
                result[1] = pre.val;
                result[0] = root.val;
            }
        }
        pre = root;
        findTwoError(root.right);
    }
}

全部评论

相关推荐

我的名字是句号:接好运
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务