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

leetcode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)

时间:2019-04-30 10:53:38      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:目录   int   solution   return   roo   turn   etc   一个   def   

题目描述:

给定一个二叉树,原地将它展开为链表。

示例:

给定二叉树

    1
   /   2   5
 / \   3   4   6

将其展开为:

1
   2
       3
           4
               5
                   6

解法:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root, TreeNode*& head, TreeNode*& tail){
        if(root == NULL){
            return;
        }else{
            head = root;
            TreeNode* lhead = NULL, * ltail = NULL;
            TreeNode* rhead = NULL, * rtail = NULL;
            if(root->left == NULL && root->right == NULL){
                // leaf node
                tail = root;
            }else if(root->left == NULL){
                flatten(root->right, rhead, rtail);
                tail = rtail;
                root->left = NULL;
                root->right = rhead;
            }else if(root->right == NULL){
                flatten(root->left, lhead, ltail);
                tail = ltail;
                root->left = NULL;
                root->right = lhead;
            }else{
                flatten(root->left, lhead, ltail);
                flatten(root->right, rhead, rtail);
                ltail->left = NULL;
                ltail->right = rhead;
                tail = rtail;
                root->left = NULL;
                root->right = lhead;
            }
        }
    }
    
    void flatten(TreeNode* root) {
        TreeNode* head = NULL, * tail = NULL;
        flatten(root, head, tail);
        root = head;
    }
};

leetcode 114. 二叉树展开为链表(Flatten Binary Tree to Linked List)

标签:目录   int   solution   return   roo   turn   etc   一个   def   

原文地址:https://www.cnblogs.com/zhanzq/p/10794450.html

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