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

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

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

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整型一维数组
     */
    //存储结果集的二维数组
    int[]result = new int[2];
    int index = 1;
    TreeNode pre;
    public int[] findError (TreeNode root) {
        // write code here
        // 特判
        if(root == null){
            return result;
        }
         // 递归左子树,寻找该树符合条件的节点
        findError(root.left);
        if(pre == null){
            pre = root;
        }
        // 判断是否是出错的节点
        if(index ==1 && root.val <pre.val){
            result[index] = pre.val;
            index--;
        }
        if(index ==0 && root.val <pre.val){
            result[index] = root.val;
        }
        pre = root;
        // 递归右子树,寻找该树符合条件的节点
        findError(root.right);
        return result;
    }
}
全部评论

相关推荐

03-20 12:22
门头沟学院 Java
牛客998737654号:没有hc了吧,但是我接到到后端的面试邀请
投递美团等公司6个岗位
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务