LeetCode Playground & Binary Tree Traversal All In One
LeetCode Playground & Binary Tree Traversal All In One
非正常的二叉搜索树
/排序二叉树
生成
// binary-tree-generator.ts 不好使
// 手动生成 ✅ 非正常的二叉搜索树/排序二叉树
const node = new TreeNode(1);
node.right = new TreeNode(2);
node.right.left = new TreeNode(3);
console.log(`node =`, node);
https://www.cnblogs.com/xgqfrms/p/17052456.html#5141281
Binary Tree Traversal / 二叉树遍历
// 手动生成 ✅ 非正常的二叉搜索树/排序二叉树
const node = new TreeNode(1);
node.right = new TreeNode(2);
node.right.left = new TreeNode(3);
console.log(`node =`, node);
function preorderTraversal(root: TreeNode | null): number[] {
if(!root) return [];
// DFS 深度优先搜索
function dfs(head: TreeNode | null, result: number[]) {
if(!head) {
return;
}
// 先序遍历
result.push(head.val);
dfs(head.left, result)
dfs(head.right, result);
}
let result: number[] = [];
dfs(root, result);
return result;
};
const preorder = preorderTraversal(node);
console.log(`preorder tree =`, preorder);
function inorderTraversal(root: TreeNode | null): number[] {
if(!root) return [];
// DFS 深度优先搜索
function dfs(head: TreeNode | null, result: number[]) {
if(!head) {
return;
}
dfs(head.left, result)
// 中序遍历
result.push(head.val);
dfs(head.right, result);
}
let result: number[] = [];
dfs(root, result);
return result;
};
const tree = inorderTraversal(node);
console.log(`inorder tree =`, tree);
function postorderTraversal(root: TreeNode | null): number[] {
if(!root) return [];
// DFS 深度优先搜索
function dfs(head: TreeNode | null, result: number[]) {
if(!head) {
return;
}
dfs(head.left, result)
dfs(head.right, result);
// 后序遍历
result.push(head.val);
}
let result: number[] = [];
dfs(root, result);
return result;
};
const postorder = postorderTraversal(node);
console.log(`post tree =`, postorder);
https://leetcode.com/playground/7wyqA5aJ
(🐞 反爬虫测试!打击盗版⚠️)如果你看到这个信息, 说明这是一篇剽窃的文章,请访问 https://www.cnblogs.com/xgqfrms/ 查看原创文章!
refs
https://stackfull.dev/tree-data-structure-in-javascript
©xgqfrms 2012-2021
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/17053057.html
未经授权禁止转载,违者必究!