给定一个二叉树,原地将它展开为链表。
例如,给定二叉树
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: TreeNode* h; void dfs(TreeNode* root){ if(root!=NULL){ if(root->right!=NULL)dfs(root->right); if(root->left!=NULL)dfs(root->left); root->right=h; root->left=NULL; h=root; } } void flatten(TreeNode* root) { h=NULL; dfs(root); } };
原文地址:https://www.cnblogs.com/wz-archer/p/12589448.html
时间: 2024-11-06 09:51:47