图文课程 职群旗下

  1. 首页
  2. 所有分类
  3. Java
  4. 114. Flatten Binary Tree to Linked List

114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.

For example,
Given

1/ \25/ \\346

 

The flattened tree should look like:

1\2\3\4\5\6
代码如下:


/**

* Definition for a binary tree node.
* public class TreeNode {
*int val;

*TreeNode left;

*TreeNode right;

*TreeNode(int x) { val = x;
}


* }


*/
public class Solution {
public void flatten(TreeNode root) {
TreeNode p=root;

List<TreeNode>
list=PreOrder(root);


for(int i=1;i<list.size();i++)
{
p.right=list.get(i);

p.left=null;

p=p.right;

}



}


public List<TreeNode>
PreOrder(TreeNode root){
//
树的前序遍历
List<TreeNode>
list=new ArrayList<>();

try{
list.add(root);


if(root.left!=null)
list.addAll(PreOrder(root.left));

if(root.right!=null)
list.addAll(PreOrder(root.right));

}catch(NullPointerException e){}


return list;

}


}

 

猜你喜欢
199. Binary Tree Right Side View 理解netty对protocol buffers的编码解码
101. Symmetric Tree CentOS 6.5 下的截图方法
隐藏tabbar的属性hidesBottomBarWhenPushed React入门最好的学习实例-TodoList
file_put_contents 错误:failed to open stream: Invalid argument 一种原因 DataTable之Editor个性化设置
Linux配置环境报“/usr/local/develop-tools/apache-maven-3.3.9/bin: 是一个目录“的解决方案 CentOS6.6图文详细安装教程(有些设置大部分教程没出现过,附带网络设置等)