Leetcode Flatten Binary Tree to Linked List
程序员文章站
2022-04-27 08:53:06
...
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like: 1
\
2
\
3
\
4
\
5
\
6
关键在原来的树上,如何进行变换而且不影响继续遍历。
代码如下:
/**
* 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) {
TreeNode* now = root;
while(now)
{
if(now->left)
{
TreeNode* pre = now->left;
while(pre->right != NULL)
pre = pre->right;
pre->right = now->right;
now->right = now->left;
now->left = NULL;
}
now = now->right;
}
}
};
上一篇: Django之时钟插件的使用
下一篇: 明确了!导师再也不能让研究生干这种事!
推荐阅读
-
leetcode笔记:Invert Binary Tree
-
【LeetCode OJ 328】Odd Even Linked List
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
LeetCode 236 -- 二叉树的最近公共祖先 ( Lowest Common Ancestor of a Binary Tree ) ( C语言版 )
-
LeetCode 235--二叉搜索树的最近公共祖先 ( Lowest Common Ancestor of a Binary Search Tree ) ( C语言版 )
-
LeetCode 235. Lowest Common Ancestor of a Binary Search Tree 二叉搜索树
-
[Leetcode] 235. Lowest Common Ancestor of a Binary Search Tree
-
leetcode 235. Lowest Common Ancestor of a Binary Search Tree(二叉树的最低共同祖先)