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

来源:互联网 发布:赵泓霖网络课下载 编辑:程序博客网 时间:2024/06/05 18:37

1 解题思想

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

2 原题

Given a binary tree, flatten it to a linked list in-place. For example,Given          1        / \       2   5      / \   \     3   4   6The 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;        }    }}
0 0