156. Binary Tree Upside Down
給定一棵二元樹的根節點,將這棵樹上下顛倒並返回新的根節點。
你可以按照以下步驟將二元樹上下顛倒:原來的左子節點變成新的根節點。
原來的根節點變成新的右子節點。
原來的右子節點變成新的左子節點。
上述步驟是逐層進行的。保證每個右子節點都有一個兄弟節點(同一父節點的左節點)並且沒有子節點。
範例 :
輸入: root = [1,2,3,4,5] 輸出: [4,5,2,null,null,3,1]
Python
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def upsideDownBinaryTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root or not root.left:
return root
newRoot = self.upsideDownBinaryTree(root.left)
root.left.left = root.right
root.left.right = root
root.left = None
root.right = None
return newRoot
16.48MB, 38ms
C++
/**
* 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:
TreeNode* upsideDownBinaryTree(TreeNode* root) {
if (!root || !root->left) {
return root;
}
TreeNode* newRoot = upsideDownBinaryTree(root->left);
root->left->left = root->right;
// The original right child becomes the left child of the new root.
root->left->right = root;
// The original root becomes the right child of the new root.
root->left = nullptr;
root->right = nullptr;
return newRoot;
}
};
12.39MB, 3ms
Javascript
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val === undefined ? 0 : val);
* this.left = (left === undefined ? null : left);
* this.right = (right === undefined ? null : right);
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var upsideDownBinaryTree = function(root) {
if (!root || !root.left) {
return root;
}
const newRoot = upsideDownBinaryTree(root.left);
root.left.left = root.right;
// The original right child becomes the left child of the new root.
root.left.right = root;
// The original root becomes the right child of the new root.
root.left = null;
root.right = null;
return newRoot;
};
50MB, 65ms