剑指 Offer 55 - I. 二叉树的深度

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

 方法二、非递归,(层次遍历)

public int maxDepth(TreeNode root) {
        if (root == null) return 0;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        int res = 0;
        while (!queue.isEmpty()) {
            res++;
            int n = queue.size();
            for (int i = 0; i < n; i++) {
                TreeNode node = queue.poll();
                if (node.left != null) queue.add(node.left);
                if (node.right != null) queue.add(node.right);
            }
        }
        return res;
    }
posted @ 2020-12-17 12:24  peanut_zh  阅读(51)  评论(0编辑  收藏  举报