226. Invert Binary Tree
https://leetcode.com/problems/invert-binary-tree/description/
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9Output:
4
/ \
7 2
/ \ / \
9 6 3 1Trivia: This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off.
Thoughts
看到二叉树就先想分治,假设左右子树已经翻转,那在root把左右子树掉个个即可。 注意要把左右子树先存起来,别直接把调完的fit进新调用。
Code
Analysis
时间复杂度为节点树O(n)
Ver. 2
用stack的traversal实现. 时间O(N), 空间O(h).
Functional
这段代码体现的思维,就是旧树到新树的映射——对一颗二叉树而言,它的镜像树就是左右节点递归镜像的树。
这段代码最终达到的目的同样是翻转二叉树,但是它得到结果的方式和 python 代码有着本质的差别:通过描述一个 旧树->新树 的映射,而不是描述“从旧树得到新树应该怎样做”来达到目的。
Last updated
Was this helpful?