广度优先遍历 BFS
解题思路
实现代码
var preorder = function (root) {
const res = [];
if (root === null) return res;
const stack = [];
stack.push(root);
while (stack.length) {
let len = stack.length;
while (len) {
const node = stack.pop();
res.push(node.val);
node.children.reverse().forEach(item => {
stack.push(item);
});
len--;
}
}
return res;
};
深度优先遍历 DFS
实现代码
var preorder = function (root) {
const res = [];
const dfs = (root) => {
if (root === null) return;
res.push(root.val);
root.children.forEach(node=>{
dfs(node);
})
};
dfs(root);
return res;
};
打赏作者
您的打赏是我前进的动力
微信
支付宝
leetcode🧑💻 150. 逆波兰表达式求值
上一篇
评论