您的位置:首页 > 其它

【Leetcode】Flatten Binary Tree to Linked List

2015-11-22 11:00 330 查看
题目链接:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/

题目:

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


思路:

递归处理每个结点,如果结点左孩子为空,则无需处理。否则先将结点右孩子挂到左孩子最右边的子孙结点,然后将左孩子挂到右边,左边置空。注意,叶结点无需处理,要从叶的父结点开始处理。

算法:

public void flatten(TreeNode root) {
if (root == null)
return;
flatten(root.left);
flatten(root.right);
TreeNode p = root;
// 递归到叶的父结点,因为叶结点不需要处理
if (p.left == null) {// 左孩子为空,无需处理
return;
}
p = p.left;
while (p.right != null) // 找到p的左孩子最右边的结点 t
p = p.right;
p.right = root.right;// p的右孩子连到 t的右结点
root.right = root.left;
root.left = null;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: