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

题目描述:

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

示例:

给定二叉树

    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;
    }
};

猜你喜欢

转载自www.cnblogs.com/zhanzq/p/10794450.html