Data Structure: Tree & tree generator All In One
"use strict";
/**
*
* @author xgqfrms
* @license MIT
* @copyright xgqfrms
* @created 2022-10-10
* @modified
*
* @description树 & 遍历
* @difficulty Easy
* @ime_complexity O(n)
* @space_complexity O(n)
* @augments
* @example
* @link https://leetcode.cn/leetbook/read/data-structure-binary-tree/xe17x7/
* @solutions
*
* @best_solutions
*
*/
// export {};
const log = console.log;
// Definition for a binary tree node.
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
this.val = (val === undefined ? 0 : val);
this.left = (left === undefined ? null : left);
this.right = (right === undefined ? null : right);
}
}
// bug ❌
const treeGenerator = (list) => {
if(!list.length) return [];
// let tree = new TreeNode(list[0]);
let tree = new TreeNode();
let temp = tree;
console.log(`tree =`, tree);
for (const [i, item] of list.entries()) {
// console.log(`item =`, item);
// if(i === 0) {
// continue;
// }
temp.val = item;
console.log(`temp 1 =`, temp);
if(item !== null) {
temp.right = new TreeNode(null);
temp.left = new TreeNode(list[i + 1]);
if(i < list.length - 1) {
temp = temp.left;
}
} else {
temp.left = new TreeNode(null);
temp.right = new TreeNode(list[i + 1]);
if(i < list.length - 1) {
temp = temp.right;
}
}
console.log(`temp 2 =`, temp);
}
console.log(`tree ?=`, tree);
return tree;
}
treeGenerator([1,null,2,3]);
//
https://leetcode.cn/leetbook/read/data-structure-binary-tree/xecaj6/
LeetCode
function preOrderTraversal(root: TreeNode | null): number[] {
if(!root) return [];
// 144. 二叉树的前序遍历: root, left, right
// 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;
};
https://leetcode.com/problems/binary-tree-preorder-traversal/
https://leetcode.cn/problems/binary-tree-preorder-traversal/
refs
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载
标签:right,TreeNode,generator,temp,tree,Tree,null,Data,left From: https://www.cnblogs.com/xgqfrms/p/16803069.html