[LeetCode] Flatten Binary Tree to Linked List 解题报告
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
Given
1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like:
1 \ 2 \ 3 \ 4 \ 5 \ 6
对于这个问题,网络上有很多递归和迭代的方法,本文介绍一种非递归和迭代的方法,主要的思路很类似树的线索化。
1 1 1 / \ \ \ 2 5 转换为 2 转换为 2 / \ \ / \ \
3 4 6 3 4 3
\ \
5 4
\ \
6 5
\
6
具体思路:
将节点的左子树的最右节点的右孩子指针(初始为NULL)指向节点的右孩子,依次遍历下即可。
参考代码如下:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 class Solution { 11 public: 12 void flatten(TreeNode* root) { 13 TreeNode *cur, *pre; 14 cur = root; 15 while(cur) { 16 if (cur->left) { 17 pre = cur->left; 18 while(pre->right != NULL) { 19 pre = pre->right; 20 } 21 pre->right = cur->right; 22 cur->right = cur->left; 23 cur->left = NULL; 24 } 25 else { 26 cur = cur->right; 27 } 28 } 29 } 30 };