一、二叉树层级遍历
// 初始化二叉树 function TreeNode(val){ this.val = val; this.left = this.right =null; } function levelOrder(root) { var res = []; if(!root) return res; recusion(root,0); return res; function recusion(root,level) { if(!root) return; // 判断当前level层是否已存在元素 if(res[level]){ res[level].push(root.val); } else { res[level] = [root.val]; } if(root.left){ recusion(root.left,level+1); } if(root.right){ recusion(root.right,level+1); } } }
讯享网
二、求二叉树最大深度
讯享网// 初始化二叉树 function TreeNode(val){ this.val = val; this.left = this.right =null; } function maxDepth(root) { if(root === null){ return 0; } else { var leftDepth = maxDepth(root.left); var rightDepth = maxDepth(root.right); var childDepth = leftDepth>rightDepth?leftDepth:rightDepth; return childDepth+1; } }
三、求二叉树的最大宽度
// 初始化二叉树 function TreeNode(val){ this.val = val; this.left = this.right =null; } function maxWidth(root) { if(!root) return 0; var res = [],maxWidth = 1; recusion(root,0,0); return maxWidth; function recusion(root,level,num) { if(res[level]){ res[level].push(num); } else{ res[level] = [num]; } var tempArr = res[level]; var tempWidth = tempArr[tempArr.length-1]-tempArr[0]+1; if(tempWidth>maxWidth){ maxWidth = tempWidth; } if(root.left){ recusion(root.left,level+1,num*2+1); } if(root.right){ recusion(root.right,level+1,num*2+2); } } }
四、二叉树后续遍历
讯享网// 初始化二叉树 function TreeNode(val){ this.val = val; this.left = this.right =null; } // 后续遍历 先子节点,在右子节点,在根节点 // 中序遍历 左-根-右 // 前序遍历 根-左-右 function postorderTraversal(root) { var res = []; if(!root) return res; recusion(root); return res; function recusion(root) { if(!root) return; recusion(root.left); recusion(root.right); recusion(root.val); } }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/86582.html