LeetCode 38 Flatten Binary Tree to Linked List
来源:互联网 发布:北风网php 百度云 编辑:程序博客网 时间:2024/04/30 12:42
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
分析:
看见二叉树,首先想到递归,那么就是把左子树flattern接在root孩子,把右子树flattern接在左子树链的后面。
需要注意的是,左孩子指针要变成null.
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public void flatten(TreeNode root) { if(root==null) return; toLink(root); } public TreeNode toLink(TreeNode node){ if(node.left==null && node.right==null) return node; TreeNode rHead = null; if(node.right != null){ rHead = toLink(node.right); rHead.left = null; } TreeNode p = node; if(node.left != null){ TreeNode lHead = toLink(node.left); node.right = lHead; node.left = null; lHead.left = null; while(p.right != null) p = p.right; } p.right = rHead; return node; }}
0 0
- 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
- 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
- [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
- 安卓android studio配置
- C++ Primer学习 《IO Library》
- web开发中所遇到的状态码
- Flash应用程序域学习笔记
- UVA - 10029 Edit Step Ladders (二分+hash)
- LeetCode 38 Flatten Binary Tree to Linked List
- C语言之字符串
- ISE 综合面积报告分析
- 状态栏去掉机主图标
- uva 1395 - Slim Span poj 3522 Slim Span(最小生成树算法)
- OC方面的基础笔记:
- Windows Server 2008 Apache并行配置不正确解决办法
- 关于创业和趋势
- Android Animation(一)XML属性