[leetcode]104.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.

解法一

思路

直接用递归的方法,思路比较简单

代码

/**
 * 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) {
        if(root == null) return 0;
        int left = maxDepth(root.left);
        int right = maxDepth(root.right);
        return left > right ? left+1 : right+1;
    }
}

解法二

思路

采用层次遍历的方法,用队列来保存每一层的结点。

代码

/**
 * 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) {
        if(root == null) return 0;
        int res = 0;
        Deque<TreeNode> queue = new LinkedList<>();
        queue.addLast(root);
        while(!queue.isEmpty()) {
            res++;
            int n = queue.size();
            for(int i = 0; i < n; i++) {
                TreeNode t = queue.removeFirst();
                if(t.left != null) queue.addLast(t.left);
                if(t.right != null) queue.addLast(t.right);
            }
        }
        return res;
    }
}
posted @ 2018-10-08 10:07  shinjia  阅读(69)  评论(0编辑  收藏  举报