【LeetCode从零单排】No 114 Flatten Binary Tree to Linked List

来源:互联网 发布:最好的矩阵论教材 编辑:程序博客网 时间:2024/05/14 12:03

题目

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



代码下载:https://github.com/jimenbian/GarvinLeetCode


/********************************

* 本文来自博客  “李博Garvin“

* 转载请标明出处:http://blog.csdn.net/buptgshengod

******************************************/



0 0
原创粉丝点击