-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary-tree-inorder-traversal.js
More file actions
51 lines (45 loc) · 1.01 KB
/
binary-tree-inorder-traversal.js
File metadata and controls
51 lines (45 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* 二叉树的中序遍历
* @param {TreeNode} root
* @return {number[]}
*/
var inorderTraversal = function (root) {
// 1. 递归
const result = [];
const inOrderTraverseNode = (node) => {
if (node) {
inOrderTraverseNode(node.left);
result.push(node.val);
inOrderTraverseNode(node.right);
}
};
inOrderTraverseNode(root);
return result;
// 2. 迭代
// return inOrderTraversalIterate(root);
};
function inOrderTraversalIterate(root) {
const result = [];
const stack = [];
let curr = root;
while (stack.length > 0 || curr) {
while (curr) {
stack.push(curr);
curr = curr.left;
}
const node = stack.pop();
result.push(node.val);
if (node.right) {
curr = node.right;
}
}
return result;
}