问题描述
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
题目链接:
思路分析
给一棵二叉树,将它转化为一个靠右孩子链接的升序链表。二叉树使用中序遍历是升序的。但正常使用中序遍历会损失右孩子,所以反其道而行之。后序遍历
We use recursion to solve this problem. Use a Global TreeNode prev denotes which node should be next node to link. Then call flatten() recursively. We visit right child first, link it right child to prev, left child to null, then let itself become prev for next node to connect with.
We call flatten in right child first then left and finally itself. It is the reverse of inorder traversal.
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
TreeNode prev = null;
public void flatten(TreeNode root) {
if (root == null){
return;
}
flatten(root.right);
flatten(root.left);
root.right = prev;
root.left = null;
prev = root;
}
}
时间复杂度:O(n)
空间复杂度:O(1)