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
The flattened tree should look like:
另外也可以直接进行 转换 每次都将左边所有的节点放到右边 再将原右边的所有节点放到原左边的最后一个右节点处 代码如下:
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; } } }
相关文章推荐
- [Leetcode]Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List 解题报告
- Flatten Binary Tree to Linked list
- LeetCode Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- leetcode - Flatten Binary Tree to Linked List
- Flatten binary tree to linked list
- Leetcode: Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- LeetCode: Flatten Binary Tree to Linked List
- [面试真题] LeetCode:Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- Flatten Binary Tree to Linked List
- LeetCode Flatten Binary Tree to Linked List
- [Leetcode] Flatten Binary Tree to Linked List
- [LeetCode] Flatten Binary Tree to Linked List
- LeetCode - Flatten Binary Tree to Linked List
- leetcode Flatten Binary Tree to Linked List
- leetcode: Flatten Binary Tree to Linked List