码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode-- Flatten Binary Tree to Linked List

时间:2015-07-29 17:12:23      阅读:141      评论:0      收藏:0      [点我收藏+]

标签:

Flatten Binary Tree to Linked List

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

这个道题方法有多种,虽然下面这个很简单,但我觉得还是蛮经典。

C++代码:

class Solution {
public:
    void flatten(TreeNode* root) {
        if(!root) return;

        flatten(root->left);
        flatten(root->right);

        if (nullptr == root->left) return;

        TreeNode *p=root->left;
        while(p->right) p=p->right;
        p->right = root->right;
        root->right = root->left;
        root->left = nullptr;
    }
};

版权声明:本文为博主原创文章,未经博主允许不得转载。

LeetCode-- Flatten Binary Tree to Linked List

标签:

原文地址:http://blog.csdn.net/mennoa/article/details/47130297

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!