您的位置:首页 > 其它

Leetcode 114. Flatten Binary Tree to Linked List 二叉树到链表 解题报告

2016-09-29 13:45 477 查看

1 解题思想

这道题,其实也就是把二叉树转变成一个链表他题目里面要求的原地,其实用一个List暂存下引用也ok

2 原题

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


3 AC解

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/

/**
* 使用队列来记录遍历顺序,然后改写就好。
*/
public class Solution {
List<TreeNode> orders=new ArrayList<TreeNode>();
public void dfs(TreeNode root){
orders.add(root);
if(root.left!=null) dfs(root.left);
if(root.right!=null) dfs(root.right);
}
public void flatten(TreeNode root) {
if(root==null) return ;
dfs(root);
TreeNode last=root;
root.left=null;
root.right=null;
for(int i=1;i<orders.size();i++){
root.right=orders.get(i);
root=orders.get(i);
root.left=null;
root.right=null;
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二叉树 链表 leetcode
相关文章推荐