leetcode topic maximum depth 104. Binary Tree

topic

Given a binary tree to find its maximum depth.

The depth of the binary tree is the root node to the nodes on the longest path farthest leaf node.

Description: leaf node is a node has no child nodes.

Examples

Given binary tree [3,9,20, null, null, 15,7],
     . 3
    / \
  . 9 20 is
       / \
    15. 7

Return to its maximum depth of 3.

Code

/*
 * 二叉树的最大深度
 */
public class problem104 {
	public static class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;

		TreeNode(int x) {
			val = x;
		}
	}

	public int maxDepth(TreeNode root) {
		if(root==null) 
			return 0;
		else 
			return Math.max(maxDepth(root.left)+1, maxDepth(root.right)+1);
	}
}
Published 31 original articles · won praise 0 · Views 292

Guess you like

Origin blog.csdn.net/qq_36360463/article/details/104219219