二叉树算法题

二叉树算法题( JavaScript 实现)

二叉树的中序遍历

递归:

1
2
3
4
5
6
7
8
9
10
11
12
13
var inorderTraversal = function(root) {
let res = []
const inorder = function(root) {
if (!root) {
return;
}
inorder(root.left);
res.push(root.val);
inorder(root.right);
}
inorder(root);
return res;
};

迭代:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var inorderTraversal = function(root) {
const res = [];
const stack = [];
let cur = root;
while (stack.length || cur) {
if (cur) {
stack.push(cur);
cur = cur.left;
} else {
cur = stack.pop();
res.push(cur.val);
cur = cur.right;
}
}
return res;
};

二叉树的层序遍历

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var levelOrder = function(root) {
const res = [], queue = [];
queue.push(root);
if (root === null) {
return res;
}
while (queue.length) {
let curLevel = [];
let length = queue.length;
for (let i = 0; i < length; i++) {
let node = queue.shift();
curLevel.push(node.val);
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
res.push(curLevel);
}
return res;
};

二叉树的最大深度

1
2
3
4
5
6
var maxDepth = function(root) {
if (!root) {
return 0;
}
return Math.max(maxDepth(root.left), maxDepth(root.right)) + 1;
};

翻转二叉树

1
2
3
4
5
6
7
8
9
10
var invertTree = function(root) {
if (!root) {
return null;
}
let left = invertTree(root.left);
let right = invertTree(root.right);
root.left = right;
root.right = left;
return root;
};

二叉树的直径

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var diameterOfBinaryTree = function(root) {
let ans = 1;
function getDepth(root) {
if (!root) {
return 0;
}
let left = getDepth(root.left);
let right = getDepth(root.right);
ans = Math.max(ans, left + right + 1);
return Math.max(left, right) + 1;
}
getDepth(root);
return ans - 1;
};
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×