Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit559615e

Browse files
committed
just add two: 116, 230
1 parent64faa2e commit559615e

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/**
2+
* Definition for binary tree with next pointer.
3+
* function TreeLinkNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = this.next = null;
6+
* }
7+
*/
8+
9+
/**
10+
* Key: if a node is a parent's left child, then this node's next is its parent's right child node.
11+
* if a node is a parent node's right child, then this node's next is its parent's next node's left node.
12+
* (the parent node should have next child). The trick part is how to write code.
13+
*
14+
*@param {TreeLinkNode} root
15+
*@return {void} Do not return anything, modify tree in-place instead.
16+
*/
17+
varconnect=function(root){
18+
if(!root)return;
19+
while(root.left){
20+
// track every level, starts from the left
21+
varlevelP=root;
22+
while(levelP){
23+
levelP.left.next=levelP.right;
24+
if(levelP.next)levelP.right.next=levelP.next.left;
25+
levelP=levelP.next;
26+
}
27+
root=root.left;
28+
}
29+
};
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function TreeNode(val) {
4+
* this.val = val;
5+
* this.left = this.right = null;
6+
* }
7+
*/
8+
/**
9+
* Key: just use inorderTraversal to traverse the tree. Inorder traversal
10+
* travels the node in a ascending order because it is a BST...
11+
*
12+
*@param {TreeNode} root
13+
*@param {number} k
14+
*@return {number}
15+
*/
16+
varkthSmallest=function(root,k){
17+
varstack=[];
18+
varnode=root;
19+
20+
while(node||stack.length>0){
21+
if(node){
22+
stack.push(node);
23+
node=node.left;
24+
}else{
25+
node=stack.pop();
26+
k--;
27+
if(k===0)returnnode.val;
28+
node=node.right;
29+
}
30+
}
31+
};

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp