101. Symmetric Tree
problem description
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3But the following [1,2,2,null,3,null,3] is not:
1
/ \
2 2
\ \
3 3Note: Bonus points if you could solve it both recursively and iteratively.
algorithm thought
本质是树的层次遍历,判断每一层是否是对称的。层次遍历需要用到队列来辅助解决。得到每一层所有的值。最后遍历判断是否对称。但是对于这题,还有个技巧。对于左右子树,采取不同的策略。对于左子树,每次访问完之后,先push左及节点再push右节点。右子树,先push右再左。这样,每次从队列中拿两个节点出来,这两个节点就刚好都是对称节点。我们判断它们是否一样就行,然后继续运行。
algorithm analysis
时间复杂度就是O(n),遍历一遍树。
Last updated