Lintcode:maximum Depth of Binary Tree

Source: Internet
Author: User
Tags lintcode

Maximum Depth of Binary Tree:

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along, the longest path from the root node to the farthest leaf node.

Code:

/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/**     * @paramroot:the root of binary tree. * @return: An integer. */    Private intDepth = 0;  Public intmaxDepth (TreeNode root) {//Write your code here//Handle Corner case        if(Root = =NULL) {            return0; }        //start from the rootHelper (Root, 1); returndepth; }        Private voidHelper (TreeNode node,intcurtdepth) {        //if reach the null        if(node = =NULL) {            return; }        //Refresh Depth        if(Curtdepth >depth) {Depth=curtdepth; }        //go for left and rightHelper (Node.left, curtdepth + 1); Helper (node.right, curtdepth+ 1); }}

THR trick here's to set the depth variable and refresh it in the helper method, helper method is a Recu Rsive method, the return condition is when we reach the null node.

Lintcode:maximum Depth of Binary Tree

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.