ITeye博客

Flatten Binary Tree to Linked List

KickCode · 2016-02-09 05:20 · Leetcode · 编程语言 · Markdown

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

给定一个二叉树,要求我们将它装换成一个链表的形式。我们从左边开始,假设当前节点为root,我们首先保存root的左孩子leftNode和右孩子rightNode,然后将root的左孩子作为它的右孩 子,然后让root的左孩子为空(root.right = leftNode,root.left = null), 接下来将当然的右孩子也就是root.right(这是新的右孩子,要把这个序列的最后一个节点指向以前的右孩子)指向以前的右孩子rightNode。代码如下:


/**
 * Definition for a binary tree node.
 * 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;
        flatten(root.left);
        flatten(root.right);
        TreeNode leftNode = root.left;
        TreeNode rightNode = root.right;
        root.left = null;
        root.right = leftNode;
        while(root.right != null) {
            root = root.right;
        }
        root.right = rightNode;
    }
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。