---
title: "Flatten Binary Tree to Linked List"
author: "KickCode"
date: "2016-02-09T05:20:49Z"
tags: []
categories: ["编程语言"]
slug: "flatten-binary-tree-to-linked-list"
draft: false
lastmod: "2016-02-09T05:20:49Z"
id: 2276102
url: "https://kickcode.iteye.com/blog/2276102"
---

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。代码如下：

```java

/**
 * 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;
    }
}

```