标签:cli root 简单 函数 btn node http void pre
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
public class Solution { public void flatten(TreeNode root) { if (root == null) { return; } flatten(root.left); flatten(root.right); if (root.left != null && root.right != null) { TreeNode tmp = root.right; root.right = root.left; root.left = null; while (root.right != null) { root = root.right; } root.right = tmp; } if (root.left != null) { root.right = root.left; root.left = null; } } }
代码不够简洁,看了top solution,人家写的就很好。。。看完之后写的
public class Solution { private TreeNode pre = null; public void flatten(TreeNode root) { if (root == null) { return; } flatten(root.right); flatten(root.left); root.right = pre; root.left = null; pre = root; } }
不过两种思路不太一样,我是root右边不为空的话就把右边的先存起来,把左边的接到右边,再把左边的尾部指向tmp,而第二种方法是从右边开始,pre都指向该接在上一层末尾的地方,简洁了很多。可以学习。很好奇下次再做这道题能不能直接写出这种方法。。。先存起来,以后回顾一下。。。
Flatten Binary Tree to Linked List Leetcode
标签:cli root 简单 函数 btn node http void pre
原文地址:http://www.cnblogs.com/aprilyang/p/6357334.html