星空网 > 软件开发 > Java

114. 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
代码如下:
 1 /** 2  * Definition for a binary tree node. 3  * public class TreeNode { 4  *   int val; 5  *   TreeNode left; 6  *   TreeNode right; 7  *   TreeNode(int x) { val = x; } 8  * } 9 */10 public class Solution {11   public void flatten(TreeNode root) {12     TreeNode p=root;13     List<TreeNode> list=PreOrder(root);14 15    for(int i=1;i<list.size();i++)16     {17      p.right=list.get(i);18      p.left=null;19      p=p.right;20     }21     22   }23   public List<TreeNode> PreOrder(TreeNode root){//树的前序遍历24     List<TreeNode> list=new ArrayList<>();25     try{26      list.add(root);27     28     if(root.left!=null)29      list.addAll(PreOrder(root.left));30     if(root.right!=null)31      list.addAll(PreOrder(root.right));32     }catch(NullPointerException e){}33     return list;34   }35 }

 




原标题:114. Flatten Binary Tree to Linked List

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

东莞到三明物流专线:https://www.goluckyvip.com/tag/97938.html
东莞到越南专线:https://www.goluckyvip.com/tag/97939.html
东莞到三明市物流专线:https://www.goluckyvip.com/tag/97940.html
深圳到越南物流专线:https://www.goluckyvip.com/tag/97941.html
深圳到越南专线货运:https://www.goluckyvip.com/tag/97942.html
惠州到越南物流专线:https://www.goluckyvip.com/tag/97943.html
零售晚报:携程发布318成绩单 近800万商家GMV增长101% :https://www.kjdsnews.com/a/1836405.html
19点聊电商:百度云:大模型应用元年 企业如何先“卷”一步? :https://www.kjdsnews.com/a/1836406.html
相关文章
我的浏览记录
最新相关资讯
海外公司注册 | 跨境电商服务平台 | 深圳旅行社 | 东南亚物流