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

LeetCode OJ:Flatten Binary Tree to Linked List(捋平二叉树)

时间:2015-10-26 00:02:41      阅读:155      评论:0      收藏:0      [点我收藏+]

标签:

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

也就是说用先序遍历的方式将所有的节点都放到右侧来,我这里的方法的主要思想就是每次左侧存在节点的时候就将其原封不动的搬移到右侧来,代码如下:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     void flatten(TreeNode* root) {
13         while(root){
14             if(root->left){
15                 TreeNode * leftBegin = root->left;
16                 root->left = NULL;
17                 TreeNode * leftEnd = leftBegin;
18                 while(leftEnd->right)
19                     leftEnd = leftEnd->right;
20                 TreeNode * tmpRight = root->right;
21                 root->right = leftBegin;
22                 leftEnd->right = tmpRight;
23             }
24             root = root->right;
25         }
26     }
27 };

 

LeetCode OJ:Flatten Binary Tree to Linked List(捋平二叉树)

标签:

原文地址:http://www.cnblogs.com/-wang-cheng/p/4909780.html

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