Title Description
Given a binary tree, place it expands the list.
Ideas analysis
- A thought: every time the root of the right subtree transferred to the left of the rightmost sub-tree node.
- Thinking two: If you order recursive solution before use, store the root right subtree, and then recursively transfer time out. It may be used after preorder solution, so that no problem subtree node.
Code
/**
* 非递归解法
*
* @param root
*/
public void flatten(TreeNode root) {
if (root == null) {
return;
}
while (root != null) {
if (root.left == null) {
root = root.right;
} else {
TreeNode pre = root.left;
while (pre.right != null) {
pre = pre.right;
}
pre.right = root.right;
root.right = root.left;
root.left = null;
root = root.right;
}
}
}
/**
* 递归解法,后序遍历
*/
private TreeNode pre = null;
public void flatten1(TreeNode root) {
if (root == null) {
return;
}
flatten1(root.right);
flatten1(root.left);
root.right = pre;
root.left = null;
pre = root;
}