LeetCode-Maximum Depth of Binary Tree

来源:互联网 发布:js打开无导航栏新窗口 编辑:程序博客网 时间:2024/06/06 01:32

递归方法非常简单 只要判断左右depth 取max+1就行

public class Solution {    public int maxDepth(TreeNode root) {        if ( root == null )            return 0;        int left = maxDepth(root.left);        int right = maxDepth(root.right);        return Math.max(left,right)+1;            }}


iterative:bfs, 和level order traversal一样 注意level最开始值是0,和mindepth最开始值取1不一样。因为min在循环中碰到叶子就停了 没有最后的加一

public class Solution {    public int maxDepth(TreeNode root) {        if ( root == null )            return 0;        int level = 0;        Queue <TreeNode> que = new LinkedList<TreeNode>();        que.offer(root);        while ( !que.isEmpty()){            int num = que.size();            for ( int i = 0; i < num; i ++ ){                TreeNode cur = que.poll();                if ( cur.left != null )                    que.offer(cur.left);                if ( cur.right != null )                    que.offer(cur.right);            }            level ++;        }        return level;    }}


0 0
原创粉丝点击