添加 problem 110

This commit is contained in:
YDZ
2019-05-17 08:25:33 +08:00
parent 00d0bca8e7
commit 5da3bbfefe
3 changed files with 149 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
package leetcode
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
leftHight := depth(root.Left)
rightHight := depth(root.Right)
return abs(leftHight-rightHight) <= 1 && isBalanced(root.Left) && isBalanced(root.Right)
}
func depth(root *TreeNode) int {
if root == nil {
return 0
}
return max(depth(root.Left), depth(root.Right)) + 1
}

View File

@@ -0,0 +1,74 @@
package leetcode
import (
"fmt"
"testing"
)
type question110 struct {
para110
ans110
}
// para 是参数
// one 代表第一个参数
type para110 struct {
one []int
}
// ans 是答案
// one 代表第一个答案
type ans110 struct {
one bool
}
func Test_Problem110(t *testing.T) {
qs := []question110{
question110{
para110{[]int{3, 4, 4, 5, NULL, NULL, 5, 6, NULL, NULL, 6}},
ans110{false},
},
question110{
para110{[]int{1, 2, 2, NULL, 3, 3}},
ans110{true},
},
question110{
para110{[]int{}},
ans110{true},
},
question110{
para110{[]int{1}},
ans110{true},
},
question110{
para110{[]int{1, 2, 3}},
ans110{true},
},
question110{
para110{[]int{1, 2, 2, 3, 4, 4, 3}},
ans110{true},
},
question110{
para110{[]int{1, 2, 2, NULL, 3, NULL, 3}},
ans110{true},
},
}
fmt.Printf("------------------------Leetcode Problem 110------------------------\n")
for _, q := range qs {
_, p := q.ans110, q.para110
fmt.Printf("【input】:%v ", p)
rootOne := Ints2TreeNode(p.one)
fmt.Printf("【output】:%v \n", isBalanced(rootOne))
}
fmt.Printf("\n\n\n")
}

View File

@@ -0,0 +1,50 @@
# [110. Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree/)
## 题目
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
```c
3
/ \
9 20
/ \
15 7
```
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
```c
1
/ \
2 2
/ \
3 3
/ \
4 4
```
Return false.
## 题目大意
判断一棵树是不是平衡二叉树。平衡二叉树的定义是:树中每个节点都满足左右两个子树的高度差 <= 1 的这个条件。
计算树的高度是第 104 题。