网站高中建设工具,网站主页面最开始在哪里做,邢台织梦模板建站,微信管理系统后台递归三部曲#xff1a;
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
#xff08;1#xff09;确定参数和返回值#xff0c;
参数为传入根节点#xff0c;再根据此遍历左右左右树的节点。返回最短路径#xff0c;即int类型。
#xff08;2#xff09;确…递归三部曲
最小深度是从根节点到最近叶子节点的最短路径上的节点数量
1确定参数和返回值
参数为传入根节点再根据此遍历左右左右树的节点。返回最短路径即int类型。
2确定终止条件:
当root节点为空时返回0 当 root 节点左右孩子都为空时返回 1
(3)确定单层递归条件
当 root 节点左右孩子有一个为空时返回不为空的孩子节点的深度 当 root 节点左右孩子都不为空时返回左右孩子较小深度的节点值 我最开始写的 int leftDepth getDepth(node-left); int rightDepth getDepth(node-right); int result 1 min(leftDepth, rightDepth); return result; 这样就犯了误区; class Solution {public int minDepth(TreeNode root) {if(rootnull){return 0;}else if(root.leftnullroot.rightnull){return 1;}else{int leftDepthminDepth(root.left);//遍历的9int rightDepthminDepth(root.right);//遍历的20最终为2if(leftDepth0){return rightDepth1;}else if(rightDepth0){return leftDepth1;}else{int curMath.min(leftDepth,rightDepth)1;return cur;}}}
}