> For the complete documentation index, see [llms.txt](https://junnie.gitbook.io/nine-chapter/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://junnie.gitbook.io/nine-chapter/2.binary-tree/453.flatten-binary-tree-to-linked-list.md).

# 453.Flatten Binary Tree to Linked List

## 1.Description(Easy)

Flatten a binary tree to a fake "linked list" in pre-order traversal.

Here we use the\_right\_pointer in TreeNode as the \_next \_pointer in ListNode.

### Notice

Don't forget to mark the left child of each node to null. Or you will get Time Limit Exceeded or Memory Limit Exceeded.

**Example**

```
              1
               \
     1          2
    / \          \
   2   5          3
  / \   \          \
 3   4   6          4
                     \
                      5
                       \
                        6
```

## 2.Code

用一个栈存放顺序每次放进去就peek出来，再依次放出来连接。别忘了把left设置成null.如果是最后把right设置成null.

```
public void flatten(TreeNode root){
    if(root==null){
        return;
    }
    Stack<TreeNode> st=new Stack<TreeNode>();
    st.push(root);
    while(!st.empty()){
        TreeNode node=st.pop();
        if(node.right!=null){
            st.push(node.right);
        }
        if(node.left!=null){
            st.push(node.left);
        }

        //connect
        node.left=null; //every node left is null;
        if(!st.empty()){
            node.right=st.peek(); //only peek.
        }else{
            node.right=null;
        }
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://junnie.gitbook.io/nine-chapter/2.binary-tree/453.flatten-binary-tree-to-linked-list.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
