LeetCode算法笔记-Day50
101. Symmetric Tree
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
example:
1 2 3 4 5 6 7 8 9 10 11 12 13
| this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3
But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3
|
Analyse:
递归
根据上面信息可以总结出递归函数的两个条件:
终止条件:
- left 和 right 不等,或者 left 和 right 都为空
- 递归的比较 left,left 和 right.right,递归比较 left,right 和 right.left
My Answer:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
var isSymmetric = function(root) { let dfs = (_left,_right) => { if(_left === _right) return true; if(_left && _right && _left.val == _right.val){ return dfs(_left.left,_right.right) && dfs(_left.right,_right.left); } return false; }
return root ? dfs(root.left,root.right) : true; };
|