Skip to content

Commit

Permalink
feat: azl397985856#92 增加注释 #236增加扩展 backlog增加题目
Browse files Browse the repository at this point in the history
  • Loading branch information
luzhipeng committed Apr 30, 2019
1 parent 9782d62 commit 2f9b3bb
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 5 deletions.
61 changes: 61 additions & 0 deletions backlog/538.convert-bst-to-greater-tree.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
/*
* @lc app=leetcode id=538 lang=javascript
*
* [538] Convert BST to Greater Tree
*
* https://leetcode.com/problems/convert-bst-to-greater-tree/description/
*
* algorithms
* Easy (50.04%)
* Total Accepted: 75.4K
* Total Submissions: 149K
* Testcase Example: '[5,2,13]'
*
* Given a Binary Search Tree (BST), convert it to a Greater Tree such that
* every key of the original BST is changed to the original key plus sum of all
* keys greater than the original key in BST.
*
*
* Example:
*
* Input: The root of a Binary Search Tree like this:
* ⁠ 5
* ⁠ / \
* ⁠ 2 13
*
* Output: The root of a Greater Tree like this:
* ⁠ 18
* ⁠ / \
* ⁠ 20 13
*
*
*/
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
var convertBST = function(root) {
let res = 0;
function r(root) {
if (root === null) return null;

r(root.right);

root.val += res;

res = +root.val;

r(root.left);

return root;
}
r(root);
return root;
};
3 changes: 3 additions & 0 deletions problems/236.lowest-common-ancestor-of-a-binary-tree.md
Original file line number Diff line number Diff line change
Expand Up @@ -147,3 +147,6 @@ var lowestCommonAncestor = function(root, p, q) {
};
```

## 扩展
如果递归的结束条件改为`if (!root || root.left === p || root.right === q) return root;` 代表的是嗯呢么意思,对结果有什么样的影响?

12 changes: 7 additions & 5 deletions problems/92.reverse-linked-list-ii.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,14 +89,16 @@ Output: 1->4->3->2->5->NULL
* @return {ListNode}
*/
var reverseBetween = function(head, m, n) {
// 虚拟节点,简化操作
const dummyHead = {
next: head
}

let current = dummyHead.next;
let pre = current;
let index = 0;
let current = dummyHead.next; // 当前遍历的节点
let pre = current; // 因为要反转,因此我们需要记住前一个节点
let index = 0; // 链表索引,用来判断是否是特殊位置(头尾位置)

// 上面提到的四个特殊节点
let midStartNode = null;
let preMidStartNode = null;
let midEndNode = null;
Expand All @@ -106,11 +108,12 @@ var reverseBetween = function(head, m, n) {
const next = current.next;
index++;

// reverse linked list
// 对 (m - n) 范围内的节点进行反转
if (index > m && index <= n) {
current.next = pre;
}

// 下面四个if都是边界, 用于更新四个特殊节点的值
if (index === m - 1) {
preMidStartNode = current;
}
Expand All @@ -120,7 +123,6 @@ var reverseBetween = function(head, m, n) {

if (index === n + 1) {
postMidEndNode = current;
postMidEndNode.next
}

if (index === n) {
Expand Down

0 comments on commit 2f9b3bb

Please sign in to comment.