题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
#include <queue>
#include <vector>
class Solution {
public:
    TreeNode* Convert(TreeNode* pRootOfTree) {
		if(not pRootOfTree) return nullptr;

		std::queue<TreeNode*> q;
		TreeNode* newHead{};
		auto mid = [&q, &newHead](auto&& self, TreeNode* n) {
			if(not n) return;
		    self(self, n->left);
			q.push(n);
			if(q.size() == 2) [[likely]] {
				auto l = q.front(), r = q.back();
				l->right = r;
				r->left = l;
                q.pop();
			} else {
				newHead = n;
			}
			self(self, n->right);
		};
        mid(mid, pRootOfTree);
		return newHead;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享
牛客网
牛客企业服务