二叉树的右视图
/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * 求二叉树的右视图 * @param xianxu int整型一维数组 先序遍历 * @param zhongxu int整型一维数组 中序遍历 * @return int整型一维数组 */ function solve( xianxu , zhongxu ) { // write code here function TreeNode(x){ this.val = x this.left = null this.right = null } function build(xianxu,zhongxu){ if(xianxu.length ==0 || zhongxu.length ==0) return null let root = new TreeNode(xianxu[0]) let index = zhongxu.indexOf(xianxu[0]) root.left = build(xianxu.slice(1,index+1),zhongxu.slice(0,index)) root.right = build(xianxu.slice(index+1),zhongxu.slice(index+1)) return root } let root = build(xianxu,zhongxu) let result = [] let stack = [root] let temp = [] let len = 0 while(len = stack.length){ for(let i=0;i<len;i++){ let node = stack.shift() temp.push(node.val) if(node.left) stack.push(node.left) if(node.right) stack.push(node.right) } result.push(temp.pop()) temp.length = 0 } return result } module.exports = { solve : solve };
树算法 文章被收录于专栏
树相关算法