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

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

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);
    }
};
全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务