[LeetCode][JavaScript]Symmetric Tree

Symmetric Tree

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree is symmetric:

    1
   / \
  2   2
 / \ / \
3  4 4  3

 

But the following is not:

    1
   / \
  2   2
   \   \
   3    3
https://leetcode.com/problems/symmetric-tree/
 
 
 
 
 
判断树是不是左右对称的。
技巧是递归的时候交换左右节点的左右子树。
 
 1 /**
 2  * Definition for a binary tree node.
 3  * function TreeNode(val) {
 4  *     this.val = val;
 5  *     this.left = this.right = null;
 6  * }
 7  */
 8 /**
 9  * @param {TreeNode} root
10  * @return {boolean}
11  */
12 var isSymmetric = function(root) {
13     if(root === null) return true;
14     return symmetric(root.left, root.right);
15 
16     function symmetric(leftNode, rightNode){
17         if(leftNode === null && rightNode === null) return true;
18         if(leftNode !== null && rightNode !== null){
19             if(leftNode.val !== rightNode.val) return false;
20             return symmetric(leftNode.left, rightNode.right) 
21                 && symmetric(leftNode.right, rightNode.left);
22         }else{
23             return false;
24         }
25     }
26 };

 

 
 

你可能感兴趣的:([LeetCode][JavaScript]Symmetric Tree)