您的位置:首页 > 其它

Flatten Binary Tree to Linked List

2015-01-04 11:11 267 查看
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 class Solution {
List<Integer> res=new ArrayList<Integer>();
public void flatten(TreeNode root) {
if(root==null)return ;
preorder(root);
TreeNode tmp=root;
for(int i=1;i<res.size();i++){
TreeNode n=new TreeNode(res.get(i));
tmp.right=n;
tmp.left=null;
tmp=n;
}
}
public void preorder(TreeNode root){
if(root==null)return;
res.add(root.val);
preorder(root.left);
preorder(root.right);
}
}

另外也可以直接进行 转换 每次都将左边所有的节点放到右边 再将原右边的所有节点放到原左边的最后一个右节点处 代码如下:
public class Solution {
public void flatten(TreeNode root) {
if(root==null) return ;
while(root!=null){
TreeNode tmp=root.right;
root.right=root.left;
root.left=null;
TreeNode p=root;
while(p.right!=null){
p=p.right;
}
p.right=tmp;
root=root.right;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  binary List 遍历