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

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

解题思路

中序遍历二叉搜索树,用指针pre记录上一个访问的节点 ,找到两个逆序处cur.val < pre.val即可,注意的是第一次first=[prev, cur]中的pre, 第二次second=[prev, cur]中的cur。 因为题意最终要求返回的结果升序排列,所以返回new int{second.val, first.val}

实现代码

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整型一维数组
     */
    public int[] findError (TreeNode root) {
        // write code here
        if(root == null || (root.left == null && root.right == null)){
            return new int[]{-1, -1};
        }
        Stack stack = new Stack<>();
        TreeNode cur = root;
        TreeNode pre = null;
        TreeNode first = null;
        TreeNode second = null;
        while(!stack.isEmpty() || cur != null){
            while(cur != null){
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            if(pre != null && cur.val < pre.val){
                if(first == null){
                    first = pre;
                }
                else{
                    second = cur;
                    break;
                }
            }
            pre = cur;
            cur = cur.right;
        }
        return new int[]{second.val, first.val};
    }
}

 

 

你可能感兴趣的:(算法)