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

Maximum Depth of Binary Tree

array ret pub ++ html null solution pty int

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.

分析:用層次遍歷,記錄下訪問深度即可。參考 http://www.cnblogs.com/baichangfu/p/7461433.html

JAVA CODE

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 
*/ class Solution { public int maxDepth(TreeNode root) { int deep = 0; Queue<TreeNode> queue = new ArrayDeque<>(); Queue<Integer> queue1 = new ArrayDeque<>(); if(root!=null){ queue.offer(root); queue1.offer(new Integer(deep++)); }
while(!queue.isEmpty()){ root = queue.poll(); int hh = queue1.poll().intValue(); if(deep == hh){ deep++; } if(root.left!=null){ queue.offer(root.left); queue1.offer(new Integer(deep)); }
if(root.right!=null){ queue.offer(root.right); queue1.offer(new Integer(deep)); } } return deep; } }

Maximum Depth of Binary Tree