Voyz's Studio.

LeetCode算法笔记--对称二叉树

字数统计: 205阅读时长: 1 min
2020/12/25 Share

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
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {boolean}
*/
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;
};
CATALOG
  1. 1. LeetCode算法笔记-Day50
    1. 1.1. 101. Symmetric Tree
    2. 1.2. Analyse:
      1. 1.2.1. 递归
      2. 1.2.2. My Answer: