Lintcode阶梯训练~算法

将二叉树拆成链表

2017-06-27  本文已影响65人  lyoungzzz

描述

将一棵二叉树按照前序遍历拆解成为一个假链表。所谓的假链表是说,用二叉树的 right 指针,来表示链表中的 next 指针。

注意事项

不要忘记将左儿子标记为 null,否则你可能会得到空间溢出或是时间溢出。

样例

                1
                  \
     1             2
    / \               \
   2   5    =>         3
  / \   \                \
 3   4   6                 4
                             \
                               5
                                 \
                                  6

标签

二叉树&深度优先搜索

相关题目

Flattern 2D Vector & 摊平嵌套的链表 &将二叉树按照层级转换为链表 &
将二叉查找树转换为双链表&排序链表转换为二叉树

代码实现

/**
 * 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
     */
    public void flatten(TreeNode root) {
         helper(root);
    }
    // flatten root and return the last node
    private TreeNode helper(TreeNode root) {
        if (root == null) {
            return root;
        }
        TreeNode leftLast = helper(root.left);
        TreeNode rightLast = helper(root.right);

        // connect leftLast to root.right
        //root.right 接到leftLast的右子树
        //root.left置null
        if (leftLast != null) {
            leftLast.right = root.right;
            root.right = root.left;
            root.left = null;
        }
        //返回新链表的最后一个节点
        //因为是前序遍历,必然先判断右子树,再左子树,最后根节点
        if (rightLast != null) {
            return rightLast;
        }
        if (leftLast != null) {
            return leftLast;
        }
        return root;
    }
}
上一篇 下一篇

猜你喜欢

热点阅读