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
一刷
题解:只保留右子树。我们先用right-left-mid的顺序遍历,把前一个访问的用prev存起来。
private 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;
}
二刷:
按照right-left-mid的顺序遍历这棵树。那么对于新的root, prev为就会是mid-left-right这种preorder, root的右子树为prev, 左子树为null
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private TreeNode prev = null;
public void flatten(TreeNode root) {
//preorder
if(root == null) return;
flatten(root.right);
flatten(root.left);
root.left = null;
root.right = prev;
prev = root;
}
}
三刷
post order traverse : right, left, root
root.right = prev;
root.left = null;
prev = root;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
private 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;
}
}