update 0112.路径总和: 优化 java 和 js 部分代码格式

This commit is contained in:
Yuhao Ju
2022-12-03 10:29:45 +08:00
committed by GitHub
parent 2b0239d02e
commit 0b251be446

View File

@ -33,7 +33,7 @@
* 112.路径总和
* 113.路径总和ii
这道题我们要遍历从根节点到叶子节点的路径看看总和是不是目标和。
这道题我们要遍历从根节点到叶子节点的路径看看总和是不是目标和。
### 递归
@ -167,7 +167,7 @@ public:
};
```
**是不是发现精简之后的代码,已经完全看不出分析的过程了,所以我们要把题目分析清楚之后,追求代码精简。** 这一点我已经强调很多次了!
**是不是发现精简之后的代码,已经完全看不出分析的过程了,所以我们要把题目分析清楚之后,追求代码精简。** 这一点我已经强调很多次了!
### 迭代
@ -351,28 +351,34 @@ class solution {
if(root == null) return false;
stack<treenode> stack1 = new stack<>();
stack<integer> stack2 = new stack<>();
stack1.push(root);stack2.push(root.val);
stack1.push(root);
stack2.push(root.val);
while(!stack1.isempty()) {
int size = stack1.size();
for(int i = 0; i < size; i++) {
treenode node = stack1.pop();int sum=stack2.pop();
treenode node = stack1.pop();
int sum = stack2.pop();
// 如果该节点是叶子节点了同时该节点的路径数值等于sum那么就返回true
if(node.left==null && node.right==null && sum==targetsum)return true;
if(node.left == null && node.right == null && sum == targetsum) {
return true;
}
// 右节点,压进去一个节点的时候,将该节点的路径数值也记录下来
if(node.right != null){
stack1.push(node.right);stack2.push(sum+node.right.val);
stack1.push(node.right);
stack2.push(sum + node.right.val);
}
// 左节点,压进去一个节点的时候,将该节点的路径数值也记录下来
if(node.left != null) {
stack1.push(node.left);stack2.push(sum+node.left.val);
stack1.push(node.left);
stack2.push(sum + node.left.val);
}
}
}
return false;
}
}
```
### 0113.路径总和-ii