力扣114. 二叉树展开为链表

  • 思路:
    • 根据二叉树前序遍历:根-左子树-右子树;
    • 要按照前序遍历将二叉树展开,则遍历节点右子树需要挂载到左子树“最右”节点右子树上;
    • 则当前节点 current 左子树 next = current->left 的最右节点 rightmost :
      • TreeNode* rightmost = next;
        while (rightmost->right != nullptr) {
            rightmost = rightmost->right;
        }

    • 将当前节点右子树挂载到左子树“最右”节点的右子树上:rightmost->right = current->right;
    • 则当前节点 current 展开完成,将其左子树按照要求置 nullptr,右子树挂载其左子树节点:current->left = nullptr;current->right = next;
    • 迭代下一个需要展开的节点对应的树;
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    void flatten(TreeNode* root) {
        TreeNode *current = root;
        while (current != nullptr) {
            if (current->left != nullptr) {
                TreeNode* next = current->left;
                TreeNode* rightmost = next;
                while (rightmost->right != nullptr) {
                    rightmost = rightmost->right;
                }
                rightmost->right = current->right;

                current->left = nullptr;
                current->right = next;
            }

            current = current->right;
        }
    }
};

你可能感兴趣的:(力扣实践,leetcode,链表,算法)