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