题目:
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
题意:
给定一棵二叉树,将其自身变为单链表。
比如,给定
1
/ \
2 5
/ \ \
3 4 6
转化成的扁平树如下图所示:
1 \ 2 \ 3 \ 4 \ 5 \ 6
算法分析:
* 此方法在root node上直接操作,先暂时保存左右子树,如果root有左子树,把root.right附成root.left,root.left归null,再在已经是右子树的左子树上
* 找rightmost 的node,把之前存住的right子树放在rightmost.right上即可。
* 做完一遍以后,这时root的左子树已经已经被嫁接到了右子树和root之间,原来的左子树变成null,可以进行root.right的递归了。
AC代码:
<span style="font-family:Microsoft YaHei;font-size:12px;">/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
public void flatten(TreeNode root)
{
if(root == null) return;
if(root.left != null)
{
TreeNode left = root.left;
TreeNode right = root.right;
root.left = null;
root.right = left;
TreeNode rightMost = root.right;
while(rightMost.right != null)
{
rightMost = rightMost.right;
}
rightMost.right = right;
}
flatten(root.right);
}
}</span>