keep learning, keep coding!
Problem - Invert Binary Tree
Given the root of a binary tree, invert the tree, and return its root.
翻譯蒟蒻
對一個二元樹進行反轉操作(反轉就是將每個節點的左右子樹交換位置),並返回反轉後的二元樹的根節點。
如果原始的二元樹是這樣的:
經過反轉後,樹的結構變為:
使用遞迴,對樹的每一個節點進行左右子樹的交換操作,一直迭代到樹的底部。
Example 1:
1 2
| Input: root = [4,2,7,1,3,6,9] Output: [4,7,2,9,6,3,1]
|
Example 2:
1 2
| Input: root = [2,1,3] Output: [2,3,1]
|
Example 3:
1 2
| Input: root = [] Output: []
|
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
|
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