zoukankan      html  css  js  c++  java
  • 刷题104. Maximum Depth of Binary Tree

    一、题目说明

    题目104. Maximum Depth of Binary Tree,求二叉树的最大高度。难度是Easy!

    二、我的解答

    按层遍历二叉树,就可以计算最大深度。下面是非递归算法:

    class Solution{
    	public:
    		int maxDepth(TreeNode* root){
    			queue<TreeNode*> q;
    			TreeNode* p;
    			if(root==NULL) return 0;
    			q.push(root);
    			int maxDep = 0;
    			int curLevelNum = 1,nextLevelNum = 0;
    			while(! q.empty()){
    				for(int i=0;i<curLevelNum;i++){
    					p = q.front();
    					q.pop();
    					
    					if(p->left !=NULL){
    						q.push(p->left);
    						nextLevelNum++;
    					}
    					if(p->right !=NULL){
    						q.push(p->right);
    						nextLevelNum++;
    					}
    				}
    				curLevelNum = nextLevelNum;
    				nextLevelNum = 0;
    				maxDep++;
    			}
    			return maxDep;
    		}
    };
    

    性能如下:

    Runtime: 8 ms, faster than 89.13% of C++ online submissions for Maximum Depth of Binary Tree.
    Memory Usage: 19.3 MB, less than 79.12% of C++ online submissions for Maximum Depth of Binary Tree.
    

    三、优化措施

    Easy,就不优化了。

    所有文章,坚持原创。如有转载,敬请标注出处。
  • 相关阅读:
    滑动条使用
    jquery日历练习
    JQuery 教程
    JS获取各种宽度、高度的简单介绍
    如何获取元素位置
    DOM练习
    DOM
    函数
    假期练习
    Uva 253 Cube painting
  • 原文地址:https://www.cnblogs.com/siweihz/p/12266410.html
Copyright © 2011-2022 走看看