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 down to the farthest leaf node.


1 自己的代码

class TreeNode {
	int val;
	TreeNode left;
	TreeNode right;
	TreeNode(int x) { val = x; }
	}

public class MaximumDepthOfBinaryTree {
	public int maxDepth(TreeNode root) {
		if(root == null) return 0;//不要忘记这个,不然会出现空指针异常
		
		int depth = 0;
		int leftDepth = 0;
		int rightDepth = 0;
		if(root.left != null) leftDepth = maxDepth(root.left);
		if(root.right != null) rightDepth = maxDepth(root.right);
		if(leftDepth >= rightDepth) depth = leftDepth;
		else depth = rightDepth;
        return depth + 1;
    }
	
	}

你可能感兴趣的:(binary)