Leetcode 114. Binary Tree expands the list and problem-solving ideas implemented in C ++

Problem-solving ideas:

Use recursion. Left sub-tree root node, the rightmost node is the last node in the left subtree become linked list, find the node, then the right node of this node to the root of the right subtree, at the same time, the root knot point right child pointing to its left child, left child of the root becomes null, then called recursively flatten function.

 

/**
 * 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) {
        if(root == NULL) return;
        TreeNode* right = root->right;
        if(root->left){
            root->right = root->left;
            root->left = NULL;
            TreeNode* temp = root->right;
            while(temp && temp->right) temp = temp->right;
            temp->right = right;
            flatten(root->right);
        }
        else if(root->right) flatten(root->right);
    }
};

 

 

 

Guess you like

Origin blog.csdn.net/gjh13/article/details/93405065