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

二叉搜索树与双向链表

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) {
	}
};*/
class Solution {
public:
TreeNode* pre = nullptr;
TreeNode* root = nullptr;
    TreeNode* Convert(TreeNode* pRootOfTree) {
        if(pRootOfTree == nullptr) return nullptr;
		stack<TreeNode*> s;
		TreeNode* pre = nullptr;
		TreeNode* cur = nullptr;
		while(pRootOfTree != nullptr || !s.empty()) {
			while(pRootOfTree != nullptr) {
				s.push(pRootOfTree);
				pRootOfTree = pRootOfTree->left;
			}
			if(!s.empty()) {
				pRootOfTree = s.top();
				s.pop();
				if(pre) {
					pre->right = pRootOfTree;
					pRootOfTree->left = pre;
				} else {
					root = pRootOfTree;
				}
				pre = pRootOfTree;
				pRootOfTree = pRootOfTree->right;
			}
		}
		return root;
    }
};

全部评论

相关推荐

不愿吃饼的变色龙很感性:你是我见过牛客的第一个女生
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务