首页 > 代码库 > LeetCode-114 Flatten Binary Tree to Linked List
LeetCode-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
Hints:
If you notice carefully in the flattened tree, each node‘s right child points to the next node of a pre-order traversal.
分析:
使用递归,存储原始树的左子树。需要注意的是题目要求in-place,因此不能用new TreeNode(X)构造新节点并作为结果返回。
代码如下:
1 class TreeNode { 2 int val; 3 TreeNode left; 4 TreeNode right; 5 TreeNode(int x) { val = x; } 6 } 7 8 public class Solution { 9 public void flatten(TreeNode root) {10 if(root != null) {11 TreeNode left = root.left;12 TreeNode right = root.right;13 14 root.left = null;15 root.right = left;16 flatten(root.right);17 18 while(root.right != null) {19 root = root.right;20 }21 22 root.right = right;23 flatten(root.right);24 }26 }27 }
LeetCode-114 Flatten Binary Tree to Linked List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。