Leetcode-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.

思路:在求樹的最小深度算法上稍作改動就可實現找到最大深度。

AC代碼:

import java.util.ArrayList;

public class Solution {
    public int maxDepth(TreeNode root) {
        if( root == null ) return 0;
		ArrayList<TreeNode> lastLevel = new ArrayList<TreeNode>();
		int count = 1;
		lastLevel.add(root);
		while( !lastLevel.isEmpty() ){
			ArrayList<TreeNode> nextLevel = new ArrayList<TreeNode>();
			for( TreeNode treenode:lastLevel ){
				if( treenode.left != null ) nextLevel.add(treenode.left);
				if( treenode.right != null ) nextLevel.add(treenode.right);
			}
			if( nextLevel.isEmpty() ) break;
			count++;
			lastLevel = new ArrayList<TreeNode>(nextLevel);
		}
		return count;
    }
}


發佈了107 篇原創文章 · 獲贊 7 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章