zoukankan      html  css  js  c++  java
  • 剑指 Offer 55

    /**
     * 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;
        }
  • 相关阅读:
    python day01
    Mac上安装pexpect
    raid
    SSL证书制作
    linux grep命令详解
    第一轮迭代小组成员分数分配
    M1事后分析报告(Postmortem Report)
    软件发布说明
    测试报告
    week 9 scenario testing
  • 原文地址:https://www.cnblogs.com/peanut-zh/p/14148953.html
Copyright © 2011-2022 走看看