[leetcode] 156. Binary Tree Upside Down解題レポート


タイトルリンク:https://leetcode.com/problems/binary-tree-upside-down/
Given a binary tree where all the right nodes are either leaf nodes with a sibling (a left node that shares the same parent node) or empty, flip it upside down and turn it into a tree where the original right nodes turned into left leaf nodes. Return the new root.
For example:
Given a binary tree  {1,2,3,4,5}
,
    1
   / \
  2   3
 / \
4   5

return the root of the binary tree  [4,5,2,#,#,3,1] .
   4
  / \
 5   2
    / \
   3   1  

構想:各ノードの右の木は空であるか、必ず左の木の子供と右の木の子供がいるので、木の形は左に偏っている.だから私たちは一番左の子の木を最終的な新しい根の結点として、それから再帰的にその父の結点をその右の子供として、そして父の結点の右の子供をその左の子供とします.1つの非常に重要な点は、毎回必ず親の結点の左右の子供を空にしなければならない.親の結点が左の子供の右の子供に設定された後、葉の結点になったので、針を切る必要があるからだ.
コードは次のとおりです.
/**
 * 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:
    TreeNode* upsideDownBinaryTree(TreeNode* root) {
        if(root==NULL || root->left==NULL) return root;
        auto left = upsideDownBinaryTree(root->left);
        root->left->right = root;
        root->left->left = root->right;
        root->left = NULL, root->right = NULL;
        return left;
    }
};