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

LeetCode114 Flatten Binary Tree to Linked List

时间:2016-11-17 00:32:47      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:分析   bsp   树根   https   ptr   span   ref   com   lis   

Given a binary tree, flatten it to a linked list in-place. (Medium)

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         if (root == nullptr) {
14             return;
15         }
16         while (root != nullptr) {
17             if (root -> left != nullptr) {
18                 TreeNode* temp = root -> left;
19                 while (temp -> right != nullptr) {
20                     temp = temp -> right;
21                 }
22                 temp -> right = root -> right;
23                 root -> right = root -> left;
24                 root -> left = nullptr;
25             }
26             root = root -> right;
27         }
28     }
29 };

 

LeetCode114 Flatten Binary Tree to Linked List

标签:分析   bsp   树根   https   ptr   span   ref   com   lis   

原文地址:http://www.cnblogs.com/wangxiaobao/p/6071814.html

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