mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 19:44:45 +08:00
@ -142,7 +142,7 @@ int getDepth(TreeNode* node)
|
|||||||
|
|
||||||
2. 明确终止条件
|
2. 明确终止条件
|
||||||
|
|
||||||
递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的书高度为0
|
递归的过程中依然是遇到空节点了为终止,返回0,表示当前节点为根节点的树高度为0
|
||||||
|
|
||||||
代码如下:
|
代码如下:
|
||||||
|
|
||||||
@ -534,7 +534,34 @@ func abs(a int)int{
|
|||||||
return a
|
return a
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
JavaScript:
|
||||||
|
```javascript
|
||||||
|
var isBalanced = function(root) {
|
||||||
|
//还是用递归三部曲 + 后序遍历 左右中 当前左子树右子树高度相差大于1就返回-1
|
||||||
|
// 1. 确定递归函数参数以及返回值
|
||||||
|
const getDepth=function(node){
|
||||||
|
// 2. 确定递归函数终止条件
|
||||||
|
if(node===null){
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
// 3. 确定单层递归逻辑
|
||||||
|
let leftDepth=getDepth(node.left);//左子树高度
|
||||||
|
if(leftDepth===-1){
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
let rightDepth=getDepth(node.right);//右子树高度
|
||||||
|
if(rightDepth===-1){
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
if(Math.abs(leftDepth-rightDepth)>1){
|
||||||
|
return -1;
|
||||||
|
}else{
|
||||||
|
return 1+Math.max(leftDepth,rightDepth);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return getDepth(root)===-1?false:true;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
-----------------------
|
-----------------------
|
||||||
|
@ -351,6 +351,30 @@ class Solution:
|
|||||||
```
|
```
|
||||||
Go:
|
Go:
|
||||||
|
|
||||||
|
JavaScript:
|
||||||
|
1.递归版本
|
||||||
|
```javascript
|
||||||
|
var binaryTreePaths = function(root) {
|
||||||
|
//递归遍历+递归三部曲
|
||||||
|
let res=[];
|
||||||
|
//1. 确定递归函数 函数参数
|
||||||
|
const getPath=function(node,curPath){
|
||||||
|
//2. 确定终止条件,到叶子节点就终止
|
||||||
|
if(node.left===null&&node.right===null){
|
||||||
|
curPath+=node.val;
|
||||||
|
res.push(curPath);
|
||||||
|
return ;
|
||||||
|
}
|
||||||
|
//3. 确定单层递归逻辑
|
||||||
|
curPath+=node.val+'->';
|
||||||
|
node.left&&getPath(node.left,curPath);
|
||||||
|
node.right&&getPath(node.right,curPath);
|
||||||
|
}
|
||||||
|
getPath(root,'');
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user