1. 程式人生 > >[leetcode] 156. Binary Tree Upside Down 解題報告

[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  

思路: 題意是說每個結點的右子樹要麼為空, 要麼一定有一個左子樹孩子和一個右子樹孩子, 因此樹的形狀是左偏的. 所以我們要將最左邊的子樹作為最終的新根結點, 然後遞迴的將其父結點作為其右孩子,並且父結點的右孩子作為其左孩子. 一個非常重要的地方是每次一定要將父結點的左右孩子都置為空, 因為父結點設定成其左孩子的右孩子之後成了葉子結點, 需要將其指標斷掉.

程式碼如下:

/**
 * 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 || !root->left) return root;
        TreeNode *newRoot = upsideDownBinaryTree(root->left);
        root->left->left = root->right;
        root->left->right = root;
        root->left = NULL, root->right = NULL;
        return newRoot;
    }
};