Skip to content

Commit

Permalink
update: stack to queue
Browse files Browse the repository at this point in the history
  • Loading branch information
flames519 committed May 31, 2021
1 parent 58437eb commit 4a5c0cb
Showing 1 changed file with 24 additions and 24 deletions.
48 changes: 24 additions & 24 deletions problems/0102.二叉树的层序遍历.md
Original file line number Diff line number Diff line change
Expand Up @@ -1224,15 +1224,15 @@ var rightSideView = function(root) {

// 迭代
var averageOfLevels = function(root) {
const stack = [], res = [];
root && stack.push(root);
while(len = stack.length) {
const queue = [], res = [];
root && queue.push(root);
while(len = queue.length) {
let sum = 0, l = len;
while(l--) {
const {val, left, right} = stack.shift();
const {val, left, right} = queue.shift();
sum += val;
left && stack.push(left);
right && stack.push(right);
left && queue.push(left);
right && queue.push(right);
}
res.push(sum/len);
}
Expand Down Expand Up @@ -1263,15 +1263,15 @@ var averageOfLevels = function(root) {
// 迭代
const MIN_G = Number.MIN_SAFE_INTEGER;
var largestValues = function(root) {
const stack = [], res = [];
root && stack.push(root);
while(len = stack.length) {
const queue = [], res = [];
root && queue.push(root);
while(len = queue.length) {
let max = MIN_G;
while(len--) {
const {val, left, right} = stack.shift();
const {val, left, right} = queue.shift();
max = max > val ? max : val;
left && stack.push(left);
right && stack.push(right);
left && queue.push(left);
right && queue.push(right);
}
res.push(max);
}
Expand Down Expand Up @@ -1300,15 +1300,15 @@ var largestValues = function(root) {

// 迭代
var levelOrder = function(root) {
const stack = [], res = [];
root && stack.push(root);
while(len = stack.length) {
const queue = [], res = [];
root && queue.push(root);
while(len = queue.length) {
const vals = [];
while(len--) {
const {val, children} = stack.shift();
const {val, children} = queue.shift();
vals.push(val);
for(const e of children) {
stack.push(e);
queue.push(e);
}
}
res.push(vals);
Expand Down Expand Up @@ -1341,15 +1341,15 @@ var levelOrder = function(root) {

// 迭代
var connect = function(root) {
const stack = [];
root && stack.push(root);
while(len = stack.length) {
const queue = [];
root && queue.push(root);
while(len = queue.length) {
while(len--) {
const node1 = stack.shift(),
node2 = len ? stack[0] : null;
const node1 = queue.shift(),
node2 = len ? queue[0] : null;
node1.next = node2;
node1.left && stack.push(node1.left);
node1.right && stack.push(node1.right);
node1.left && queue.push(node1.left);
node1.right && queue.push(node1.right);
}
}
return root;
Expand Down

0 comments on commit 4a5c0cb

Please sign in to comment.