LeetCode题解:Flatten Binary Tree to Linked List

来源:互联网 发布:网络繁忙请稍后再试 编辑:程序博客网 时间:2024/05/19 02:21

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

题意:看不懂……弄了几棵树跑结果发现是先序遍历

解决思路:先序遍历

代码:

public class Solution {    public void flatten(TreeNode root) {        if (root == null) {            return;        }        if (root.left == null && root.right == null) {            return;        }        while (root != null) {            if (root.left == null) {                root = root.right;                continue;            }            TreeNode left = root.left;            while (left.right != null) {                left = left.right;            }            left.right = root.right;            root.right = root.left;            root.left = null;            root = root.right;        }    }}
0 0