首页 > 编程语言 > 详细

[LeetCode][JavaScript]Symmetric Tree

时间:2015-12-31 19:19:10      阅读:218      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/Liok3187/p/5092480.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!