题目:
给定一个二叉树,原地将它展开为一个单链表。
例如,给定二叉树
1
/
2 5
/ \
3 4 6
将其展开为:
1
2
3
4
5
6
链接:https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list
思路:
1、采用后序遍历的思路,左右根。
2、具体执行流程见代码注释
Python代码:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def flatten(self, root):
"""
:type root: TreeNode
:rtype: None Do not return anything, modify root in-place instead.
"""
if not root:
return root
if (not root.left and not root.right):
return root
self.flatten(root.left) # 展开左右子树
self.flatten(root.right)
temp = root.right # 备份右子树
root.right = root.left # 将root的右指针指向展开的左子树
root.left = None # 将root的左子树置空
while root.right:
root = root.right
root.right = temp # 将展开过的右子树拼接在root当前的叶子节点后面
C++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void flatten(TreeNode* root) {
if(root==nullptr){
return;
}
if(root->left==NULL && root->right==NULL){
return;
}
flatten(root->left);
flatten(root->right);
auto temp = root->right;
root->right = root->left;
root->left = NULL;
while (root->right!=NULL){
root = root->right;
}
root->right = temp;
}
};