Middle-题目53:114. Flatten Binary Tree to Linked List

原创 2016年05月31日 16:24:17

题目原文:
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

题目大意:
把一个二叉树平铺到右子树上。
题目分析:
先递归平铺左右子树,再把左子树接到根节点右孩子上即可。
源码:(language: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 ptr = root.left;
        if(ptr!=null){
            while(ptr.right!=null){
                ptr = ptr.right;
            }
            ptr.right = root.right;
            root.right = root.left;
            root.left = null;
        }
    }
}

成绩:
1ms,beats 34.42%,众数1ms,65.58%

版权声明:完整版Leetcode题解请出门左转https://github.com/cmershen1/leetcode/tree/master/docs

相关文章推荐

114. Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List 如果能够使得叶子节点的right指向其后继的话,这样就很容易展成题目要求的形式了...
  • zzIymt
  • zzIymt
  • 2016年02月19日 09:51
  • 328

LeetCode(114) Flatten Binary Tree to Linked List解题报告

Given a binary tree, flatten it to a linked list in-place.For example, Given 1 / \ ...

<LeetCode OJ> 114. Flatten Binary Tree to Linked List

Total Accepted: 84864 Total Submissions: 270352 Difficulty: Medium Given a binary tree, flatten...

LeetCode 114. Flatten Binary Tree to Linked List(摊平二叉树)

原题网址:https://leetcode.com/problems/flatten-binary-tree-to-linked-list/ Given a binary tree, flatte...
  • jmspan
  • jmspan
  • 2016年05月24日 00:19
  • 257

[LeetCode]114.Flatten Binary Tree to Linked List

【题目】 Given a binary tree, flatten it to a linked list in-place. For example, Given 1 ...

[leetcode]114. Flatten Binary Tree to Linked List

题目链接:114. Flatten Binary Tree to Linked List Given a binary tree, flatten it to a linked list in-pl...

Leetcode-114. Flatten Binary Tree to Linked List

前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN...
  • mcf171
  • mcf171
  • 2016年10月25日 19:06
  • 87

[leetcode]114. Flatten Binary Tree to Linked List@Java解题报告

https://leetcode.com/problems/flatten-binary-tree-to-linked-list/description/ Given a bin...

Leetcode 114. Flatten Binary Tree to Linked List

Given a binary tree, flatten it to a linked list in-place.For example, Given 1 / \ 2 5...

leetcode || 114、Flatten Binary Tree to Linked List

problem: Given a binary tree, flatten it to a linked list in-place. For example, Give...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:Middle-题目53:114. Flatten Binary Tree to Linked List
举报原因:
原因补充:

(最多只允许输入30个字)