将二叉树拆成链表
题目
将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。
注意事项
不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。样例
挑战
不使用额外的空间耗费。
题解
使用前序遍历的递归解法。将任意节点的左子节点切断,接到右子节点上,由于这样会造成右子节点的数据丢失,所以需在上一次递归时提前保存右子节点。
/**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
private TreeNode lastNode = null;
public void flatten(TreeNode root) {
if (root == null)
{
return;
}
if (lastNode != null)
{
lastNode.left = null;
lastNode.right = root;
}
lastNode = root;
TreeNode right = root.right;
flatten(root.left);
flatten(right);
}
}
Last Update 2016.9.18