题目
题目链接:
https://www.nowcoder.com/practice/4582efa5ffe949cc80c136eeb78795d6?tpId=196&tqId=37154&rp=1&ru=/exam/company&qru=/exam/company&sourceUrl=%2Fexam%2Fcompany&difficulty=undefined&judgeStatus=undefined&tags=&title=
相似题目链接:解法在本题的基础上稍加改造即可
https://www.lintcode.com/problem/3600
前置知识
核心知识:二叉搜索树中序遍历是递增的
参考答案Java
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* public TreeNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 the root
* @return int整型一维数组
*/
public int[] findError (TreeNode root) {
//非递归中序遍历
TreeNode cur = root;
//error1:第一个错误节点 error2:第二个错误节点
TreeNode error1 = null, error2 = null, prev = null;
Stack<TreeNode> stack = new Stack<>();
while (!stack.isEmpty() || cur != null) {
while (cur != null) {
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
if (prev != null) {
if (prev.val > cur.val && error1 == null) {
error1 = prev;
error2 = cur;
} else if (prev.val > cur.val) {
error2 = cur;
}
}
prev = cur;
cur = cur.right;
}
int[] ans = {error2.val, error1.val};
return ans;
}
}
参考答案Go
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param root TreeNode类 the root
* @return int整型一维数组
*/
func findError(root *TreeNode) []int {
//题目保证节点数大于等于3
//核心:中序遍历
var error1, error2, prev TreeNode
prevInit := false
error1Init := false
stack := []TreeNode{} //切片模拟栈
for len(stack) > 0 || root != nil {
for root != nil {
stack = append(stack, *root)
root = root.Left
}
//fmt.Println("stack的长度:", len(stack))
root = &stack[len(stack)-1]
stackBak := []TreeNode{}
for i := 0; i < len(stack)-1; i++ {
stackBak = append(stackBak, stack[i])
}
stack = stackBak
if prevInit { //prev有值了
if prev.Val > root.Val && !error1Init {
error1 = prev
error2 = *root
error1Init = true
} else if prev.Val > root.Val {
error2 = *root
}
}
prev = *root
prevInit = true
root = root.Right
}
ans := []int{error2.Val, error1.Val}
return ans
}