January 14, 2024

Viiisit [LeetCode] - 226. Invert Binary Tree

#php#javascript#ruby

keep learning, keep coding!

Problem - Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

翻譯蒟蒻

對一個二元樹進行反轉操作(反轉就是將每個節點的左右子樹交換位置),並返回反轉後的二元樹的根節點。

如果原始的二元樹是這樣的:

1
2
3
4
5
    1
/ \
2 3
/ \
4 5

經過反轉後,樹的結構變為:

1
2
3
4
5
  1
/ \
3 2
/ \
5 4

使用遞迴,對樹的每一個節點進行左右子樹的交換操作,一直迭代到樹的底部。



Solution - JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* 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 invertTree = function(root) {
if(root === null) return null;

let left = invertTree(root.left);
let right = invertTree(root.right);

root.left = right;
root.right = left;

return root;
};

Solution - Ruby

1
2
3
4
5
6
7
def invert_tree(root)
return nil if root.nil?
root.left, root.right = root.right, root.left
invert_tree(root.left)
invert_tree(root.right)
root
end

Solution - PHP

1
2
3
4
5
6
7
8
9
10
function invertTree($root) {
if ($root == null) {
return null;
}
$left = $this->invertTree($root->left);
$right = $this->invertTree($root->right);
$root->left = $right;
$root->right = $left;
return $root;
}

LeetCode 傳送門 - Invert Binary Tree