1. 程式人生 > >[LeetCode]Maximum Depth of Binary Tree

[LeetCode]Maximum Depth of Binary Tree

java lee html net htm bin 版權 urn temp

版權聲明:本文為博主原創文章。未經博主同意不得轉載。 https://blog.csdn.net/yeweiouyang/article/details/36216093

題目:給定一顆二叉樹。求二叉樹最大深度

算法:遞歸

原理:遞歸遍歷二叉樹,從底向上計數

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
	    public int maxDepth(TreeNode root) {
	        if (null == root) {
	        	return 0;
	        }
	        
	        int left = maxDepth(root.left);
	        int right = maxDepth(root.right);
	        return (left > right ?

left+1 : right+1); } }

[LeetCode]Maximum Depth of Binary Tree