maximum-depth-of-binary-tree

/**
* @author gentleKay
* 题目描述
* 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.
* 给定二叉树,求其最大深度。
* 最大深度是从根节点到最远叶节点沿最长路径的节点数。
*/

/**
 * 
 * @author gentleKay
 * 题目描述
 * 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.
 * 给定二叉树,求其最大深度。
 * 最大深度是从根节点到最远叶节点沿最长路径的节点数。
 */

public class Main04 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeNode root = new TreeNode(4);
		root.left = new TreeNode(2);
		root.left.left = new TreeNode(1);
		root.left.right  = new TreeNode(3);
		
		root.right = new TreeNode(6);
		root.right.left = new TreeNode(5);
		root.right.right = new TreeNode(7);
		root.right.right.right = new TreeNode(8);
		System.out.println(Main04.maxDepth(root));
	}
	public static class TreeNode {
		int val;
		TreeNode left;
		TreeNode right;
		TreeNode(int x) { val = x; }
	
	}
	
	public static int maxDepth(TreeNode root) {
        if (root == null) {
        	return 0;
        }
        if (root.left == null) {
        	return maxDepth(root.right)+1;
        }
        if (root.right == null) {
        	return maxDepth(root.left)+1;
        }
        return Math.max(maxDepth(root.right)+1, maxDepth(root.left)+1);
    }
}

  

上一篇:Swoft 容器使用


下一篇:Maximum Depth of Binary Tree