Skip to content

Commit

Permalink
辛苦了,小哥哥 | Merge pull request apachecn#295 from royIdoodle/master
Browse files Browse the repository at this point in the history
2 js solution added
  • Loading branch information
jiangzhonglian authored Oct 13, 2019
2 parents d1a2473 + 60e0c7a commit 4d01bfa
Show file tree
Hide file tree
Showing 2 changed files with 167 additions and 0 deletions.
90 changes: 90 additions & 0 deletions docs/Algorithm/Leetcode/JavaScript/0100._Same_Tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# 100. Same Tree

**<font color=green>难度: Easy</font>**

## 刷题内容

> 原题连接
* [https://leetcode-cn.com/problems/same-tree/](https://leetcode-cn.com/problems/same-tree/)

> 内容描述
给定两个二叉树,编写一个函数来检验它们是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。



**示例 1:**

```
输入: 1 1
/ \ / \
2 3 2 3
[1,2,3], [1,2,3]
输出: true
```

**示例 2:**

```
输入: 1 1
/ \
2 2
[1,2], [1,null,2]
输出: false
```

**示例 3:**

```
输入: 1 1
/ \ / \
2 1 1 2
[1,2,1], [1,1,2]
输出: false
```



## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

递归解法

1. 获取当前二叉树的中序遍历结果数组
2. 判断上步的数组是否是一个有序数组

代码:

```javascript
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} p
* @param {TreeNode} q
* @return {boolean}
*/
var isSameTree = function(p, q) {
if (p) {
return p && !!q && (p.val === q.val) && isSameTree(p.left, q.left) && isSameTree(p.right,q.right)
} else {
return !q
}
};
```

77 changes: 77 additions & 0 deletions docs/Algorithm/Leetcode/JavaScript/0101._Symmetric_Tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# 101. Symmetric Tree

**<font color=green>难度: Easy</font>**

## 刷题内容

> 原题连接
* [https://leetcode.com/problems/symmetric-tree/](https://leetcode.com/problems/symmetric-tree/)

> 内容描述
给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 `[1,2,2,3,4,4,3]` 是对称的。

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

但是下面这个 `[1,2,2,null,3,null,3]` 则不是镜像对称的:

```
1
/ \
2 2
\ \
3 3
```

**说明:**

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。



## 解题方案

> 思路 1
******- 时间复杂度: O(N)******- 空间复杂度: O(1)******

递归解法

代码:

```javascript
/**
* 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) {
if (!root) {
return true
}
return isMirror(root, root)
};

function isMirror(t1, t2) {
if (t1 == null && t2 == null) return true;
if (t1 == null || t2 == null) return false;
return (t1.val == t2.val)
&& isMirror(t1.right, t2.left)
&& isMirror(t1.left, t2.right);
}
```

0 comments on commit 4d01bfa

Please sign in to comment.