广度优先遍历 — 队列先进先出
深度优先遍历 — 栈 先进后出
二叉树的数据结构
function TreeNode(val, left, right) {this.val = (val===undefined ? 0 : val)this.left = (left===undefined ? null : left) // 左子树this.right = (right===undefined ? null : right) // 右子树}
求二叉树的最大深度
var maxDepth = function(root) {if(!root) {return 0;} else {const left = maxDepth(root.left);//递归左子树const right = maxDepth(root.right);//递归右子树return Math.max(left, right) + 1;//1加左节点和有节点深度的较大者}};
求二叉树的最小深度
var minDepth1 = function(root) {if(!root) return 0;if(!root.left && !root.right) return 1; // 到叶子节点 返回if(!root.left) return 1 + minDepth(root.right); // 只有右节点时 递归右节点if(!root.right) return 1 + minDepth(root.left); // 只有左节点时 递归左节点return Math.min(minDepth(root.left), minDepth(root.right)) + 1;};
求二叉树中节点的个数
const getNodeSum=function(node){if(node===null){return 0;}let leftNum=getNodeSum(node.left);let rightNum=getNodeSum(node.right);return leftNum+rightNum+1;}
求二叉树中叶子节点的个数
var findLeaves = function(root) {let ans = []const dfs = root => {if(!root) return -1let left = dfs(root.left), right = dfs(root.right)let level = Math.max(left,right)+1ans[level] = ans[level] || []ans[level].push(root.val)return level}dfs(root) // 深度优先搜索// return ans;};
