题解 | #找到搜索二叉树中两个错误的节点#
找到搜索二叉树中两个错误的节点
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;
}
}
/*
* 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;
}
}