题解 | #找到搜索二叉树中两个错误的节点#
找到搜索二叉树中两个错误的节点
http://www.nowcoder.com/practice/4582efa5ffe949cc80c136eeb78795d6
中序遍历即可,当前节点值小于之前遍历的节点即为异常值。需要注意相邻节点交换只需要判断一次,不相邻节点交换需要判断两次。
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类 the root
* @return int整型vector
*/
vector<int> errors;
TreeNode *last = nullptr;
vector<int> findError(TreeNode* root) {
// write code here
traverse(root);
return errors;
}
void traverse(TreeNode *root) {
if (!root) return;
traverse(root->left);
if (last && root->val < last->val) {
if (errors.empty()) { //相邻节点交换
errors.push_back(root->val);
errors.push_back(last->val);
}
else //非相邻节点交换需要更新较小的值
errors[0] = root->val;
}
last = root;
traverse(root->right);
}
};