二叉树的最大深度

二叉树的最大深度为根节点到最远叶子节点的最长路径上的节点数。

function maxDepth(root){
    if (!root) return 0
    return 1 + Math.max(maxDepth(root.left),maxDepth(root.right))
}

示例

let root = {
    left:{
        left:{

        },
        right:{
            left:{

            },
            right:{
                left:{

                },
                right:{
                    
                }
            }
        }
    },
    right:{
        left:{
            left:{

            },
            right:{
                
            }
        },
        right:{
            left:{
                left:{
                    left:{
                        left:null,
                        right:{
                            
                        }
                    },
                    right:{
                        
                    }
                },
                right:{
                    
                }
            },
            right:{
                
            }
        }
    }
}
maxDepth(root) //7
posted @ 2020-08-26 14:50  671_MrSix  阅读(163)  评论(0编辑  收藏  举报