二叉树的三大遍历框架
function traverse(root) {
// base case
// 前序遍历
traverse(root.left)
//中序遍历
travserse(root.right)
//后序遍历
}
解法一:采用后序遍历的框架
在题目中很明确的知道,一棵树的深度等于左,右子树的深度取最大值加上根节点的 1 为该二叉树的深度. 必须先知道,左右子树才能欧进行对比,取最大值. ==> 所以才采用后序遍历的框架.
/* function TreeNode(x) {
this.val = x;
this.left = null;
this.right = null;
} */
function TreeDepth(pRoot)
{
if(pRoot == null) return 0;
// write code here
const left = TreeDepth(pRoot.left)
const right = TreeDepth(pRoot.right)
return Math.max(left,right) + 1;
}
module.exports = {
TreeDepth : TreeDepth
};