原题
Given a binary tree, flatten it to a linked list in-place.
For example, given the following tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
Reference Answer
思路分析
可以看出来变化后每个节点其实都是指向了在先序遍历中的后一个节点。所以就通过栈的方式来先序遍历原树,如果一个节点有左节点,那么把它的右节点压栈(如果有的话),右指针指向原来的左节点;如果一个节点没有子节点,应该把它的右指针指向栈顶的节点。
Code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def flatten(self, root):
"""
:type root: TreeNode
:rtype: void Do not return anything, modify root in-place instead.
"""
temp_node = []
while root:
if root.left:
if root.right:
temp_node.append(root.right)
root.right, root.left = root.left, None
if not root.right and temp_node:
root.right = temp_node.pop()
root = root.right
C++ Version Code
/**
* 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) {
vector<TreeNode*> temp_node;
while(root){
if (root->left){
if (root->right){
temp_node.push_back(root->right);
}
root->right = root->left;
root->left = NULL;
}
if ((!root->left) && (!temp_node.empty())){
root->right = temp_node.back();
temp_node.pop_back();
}
root = root->right;
}
}
};
Note
- 这道题不是很容易想,仔细体会栈的妙用。
参考文献
[1] https://www.kancloud.cn/xnervwang/leetcode-with-python/438855