zoukankan      html  css  js  c++  java
  • leetcode Maximum Depth of Binary Tree

    返回树的深度。

    递归:

    /**
     * Definition for binary tree
     * struct TreeNode {
     *     int val;
     *     TreeNode *left;
     *     TreeNode *right;
     *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
     * };
     */
    class Solution {
    public:
        int maxDepth(TreeNode *root) 
        {
            if (!root) return 0;
            int l = maxDepth(root -> left);
            int r = maxDepth(root -> right);
            return max(l + 1, r + 1);
        }
    };

     非递归的解法:

    public int maxDepth(TreeNode root) {
        if(root == null)
            return 0;
        
        int depth = 0;
        LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        int curNum = 1; //num of nodes left in current level
        int nextNum = 0; //num of nodes in next level
        while(!queue.isEmpty()){
            TreeNode n = queue.poll();
            curNum--;
            if(n.left!=null){
                queue.add(n.left);
                nextNum++;
            }
            if(n.right!=null){
                queue.add(n.right);
                nextNum++;
            }
            if(curNum == 0){
                curNum = nextNum;
                nextNum = 0;
                depth++;
            }
        }
        return depth;
    }
    View Code
  • 相关阅读:
    进程与线程的区别与联系
    IPC 进程间通信
    sql中的group by 和 having 用法
    大端小端格式
    Spring AOP的一个比喻和IOC的作用
    volatile变量
    策略模式
    划分算法与快速排序
    希尔排序及希尔排序java代码
    红黑树
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4128650.html
Copyright © 2011-2022 走看看