给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
1
/ \
2 5
/ \ \
3 4 6
将其展开为:1
\
2
\
3
\
4
\
5
\
6来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解法:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root)
{
if(!root) return;
stack<TreeNode *> st;
st.push(root);
TreeNode *pre = NULL;
while(!st.empty())
{
TreeNode *p = st.top();
st.pop();
if(p->right) st.push(p->right);
if(p->left) st.push(p->left);
p->left = NULL;
if(!pre) pre = p;
else
{
pre->right = p;
pre = p;
}
}
}
};
博客围绕将二叉树原地展开为链表的问题展开,给出了示例二叉树及其展开后的链表形式,并提供了问题来源为力扣(LeetCode)及相关链接。
1022

被折叠的 条评论
为什么被折叠?



