【LeetCode】Flatten Binary Tree to Linked List 解题报告

来源:互联网 发布:梦想的数据 编辑:程序博客网 时间:2024/06/05 18:43

【LeetCode】Flatten Binary Tree to Linked List 解题报告

标签(空格分隔): LeetCode


题目地址:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/#/description

题目描述:

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

Ways

这个题不是很好想,这个方法是把所有的节点和其左孩子打断,然后递归把这个左节点转换为自己的右节点。

     1    / \   2   5  / \   \ 3   4   6

变成:

     1      \   2   5    \   \ 3   4   6

2是root,3是left,4是right。修改成下面这样:

再变成:

     1      \   2   5    \   \     3   6      \          4       

再变成:

     1      \          2           \            3             \              4                \             5              \               6

代码:

/** * 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;        }        TreeNode left = root.left;        TreeNode right = root.right;        root.left = null;        flatten(left);        flatten(right);        root.right = left;        TreeNode cur = root;        while(cur.right != null){            cur = cur.right;        }        cur.right = right;    }}

Date

2017 年 4 月 19 日

0 0