diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index 25b16907..a2ae2ce1 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -496,8 +496,26 @@ struct ListNode* reverseList(struct ListNode* head){ return reverse(NULL, head); } ``` -Scala: + + +PHP: +```php +// 双指针法: +function reverseList($head) { + $cur = $head; + $pre = NULL; + while($cur){ + $temp = $cur->next; + $cur->next = $pre; + $pre = $cur; + $cur = $temp; + } + return $pre; + } +``` + +Scala: 双指针法: ```scala object Solution { @@ -529,6 +547,7 @@ object Solution { cur.next = pre reverse(cur, tmp) // 此时cur成为前一个节点,tmp是当前节点 } + } ``` ----------------------- diff --git a/problems/0404.左叶子之和.md b/problems/0404.左叶子之和.md index 4ef68d3b..c0c68090 100644 --- a/problems/0404.左叶子之和.md +++ b/problems/0404.左叶子之和.md @@ -516,6 +516,44 @@ int sumOfLeftLeaves(struct TreeNode* root){ } ``` +## Scala + +**递归:** +```scala +object Solution { + def sumOfLeftLeaves(root: TreeNode): Int = { + if(root == null) return 0 + var midValue = 0 + if(root.left != null && root.left.left == null && root.left.right == null){ + midValue = root.left.value + } + // return关键字可以省略 + midValue + sumOfLeftLeaves(root.left) + sumOfLeftLeaves(root.right) + } +} +``` + +**迭代:** +```scala +object Solution { + import scala.collection.mutable + def sumOfLeftLeaves(root: TreeNode): Int = { + val stack = mutable.Stack[TreeNode]() + if (root == null) return 0 + stack.push(root) + var sum = 0 + while (!stack.isEmpty) { + val curNode = stack.pop() + if (curNode.left != null && curNode.left.left == null && curNode.left.right == null) { + sum += curNode.left.value // 如果满足条件就累加 + } + if (curNode.right != null) stack.push(curNode.right) + if (curNode.left != null) stack.push(curNode.left) + } + sum + } +} +``` -----------------------