本文主要是介绍leetcode -- 114.二叉树展开为链表,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
https://leetcode.cn/problems/flatten-binary-tree-to-linked-list/
题目中要求把链表展开为单链表,并且展开后的链表要跟二叉树的前序遍历顺序相同。
/*** Definition for a binary tree node.* struct TreeNode {* int val;* struct TreeNode *left;* struct TreeNode *right;* };*/
void flatten(struct TreeNode* root) {struct TreeNode* cur = root;while (cur != NULL){if (cur->left != NULL) {struct TreeNode* next = cur->left;struct TreeNode* pre = next;while (pre->right != NULL) {pre = pre->right;}pre->right = cur->right;cur->left = NULL;cur->right = next;}cur = cur->right;}
}
这篇关于leetcode -- 114.二叉树展开为链表的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!