二叉树及构建(留存)

35 阅读1分钟

/**

* @param {TreeNode} root

* @return {number[]}

*/

var inorderTraversal = function(root) {

//方法1:递归

let res = [];

const mid = (root) => {

if(!root) return;//本轮递归终止,返回上一次递归,相当于隐式维护了一个栈

mid(root.left);//访问左子树

console.log(root,'root----',res)

res.push(root.val);//将根节点push进数组

mid(root.right);//访问右子树

console.log(root,'root=======............',res)

}

mid(root);

console.log(res,'re--??')

return res;

};

let arr = createTree([1,2,3,4,5,6,7])

console.log('arr :>> ', arr);

console.log(inorderTraversal(arr),'-----------')

// 创建二叉树 数组 转化 为二叉树

function createTree (arr){

// 创建二叉树的节点类

class treeNode{

constructor(val, left, right){

this.val = val===undefined ? 0 : val

this.left = left === undefined ? null : left

this.right = right === undefined ? null : right

}

}

debugger

//将arr中所有的值转化为treeNode

const nodes = arr.map(item => (item!==null ? new treeNode(item) : null) )

console.log('nodes :>> ', nodes);

// 创建根节点/父节点

let root = nodes[0]

console.log('root :>> ', root);

// 定义父节点的索引值

let parentIndex = 0

// 遍历nodes中的值

let i = 1

// 如果i小于数组nodes的值就一直遍历,直到将nodes遍历完

while (i < nodes.length){

// node是nodes中的元素

const node = nodes[i]

console.log('nodes[i] ', node);

// 定义父节点,初始父节点应该是nodes[0]

let parent = nodes[parentIndex]

// 如果父节点不为空的话就,将nodes中的元素 赋给父节点的left 和 right

if(parent !== null){

parent.left = nodes[i]

i+1 >= node.length ? parent.right = null : parent.left = nodes[i+1]

// 更新父节点

parentIndex++

// 更新i的取值

i += 2

console.log('parent', parent);

}

// 如果父节点是空的话就,直接更新父节点 的索引,因为null没有left 和 right

else{

parentIndex++

}

}

console.log('root :>> 返回父节点即可', root);

// 返回父节点即可

return root

}

js如何创建二叉树/当输入是数组时,如何转换为二叉树结构?-CSDN博客