LeetCode104 Maximum Depth of Binary Tree

本文介绍了求解二叉树最大深度的经典算法实现,分别用Java、C和Python三种语言给出了具体的解决方案。通过递归遍历的方式,找到从根节点到最远叶子节点的最长路径上的节点数量。

详细见:leetcode.com/problems/maximum-depth-of-binary-tree


Java Solution: github

package leetcode;

/*
 * 	Given a binary tree, find its maximum depth.

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

import tools.TreeNode辅助.TreeNode;

public class P104_MaximumDepthOfBinaryTree {
	public static void main(String[] args) {
		
	}
	/*
	 * 	AC
	 * 	0 ms
	 */
	static class Solution {
		int max_depth = 0;
	    public int maxDepth(TreeNode root) {
	    	find_max_depth(root, 0);
	        return max_depth;
	    }
		private void find_max_depth(TreeNode root, int depth) {
			if (root == null) {
				return;
			}
			max_depth = Math.max(depth + 1, max_depth);
			find_max_depth(root.left, depth + 1);
			find_max_depth(root.right, depth + 1);
		}
	    
	}
}


C Solution: github

/*
    url: leetcode.com/problems/maximum-depth-of-binary-tree
    AC 3ms 75.91%
*/


struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
};

int _max(int a, int b) {
    return a < b ? b : a;
}

void search(struct TreeNode* root, int cnt, int* ans) {
    if (root == NULL) {
        *ans = _max(cnt, *ans);
    } else {
        search(root->left, cnt+1, ans);
        search(root->right, cnt+1, ans);
    }
}

int maxDepth(struct TreeNode* root) {
    int ans = 0;
    search(root, 0, &ans);
    return ans;
}


Python Solution: github

#coding=utf-8

'''
    url: leetcode.com/problems/maximum-depth-of-binary-tree
    @author:     zxwtry
    @email:      zxwtry@qq.com
    @date:       2017年4月27日
    @details:    Solution: 65ms 71.36%
'''

class Solution(object):
    def maxDepth(self, n):
        """
        :type n: TreeNode
        :rtype: int
        """
        if n == None: return 0
        l, cnt = [n], 0
        while len(l) != 0:
            ll = []
            for nn in l:
                if nn.left != None: ll.append(nn.left)
                if nn.right != None: ll.append(nn.right)
            l = ll
            cnt += 1
        return cnt


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值