leetcode Maximum Depth of Binary python C++

来源:互联网 发布:app软件产品说明书 编辑:程序博客网 时间:2024/05/29 04:15

又来刷下限了。都是很easy的题目。求轻喷~

就是求二叉树的高度问题。

首先想到的就是递归,递归代码超简单啊。

直接上代码:

# Definition for a  binary tree node# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    # @param root, a tree node    # @return an integer    def maxDepth(self, root):        if None == root:            return 0        else:            leftDep = self.maxDepth(root.left)+1            rightDep = self.maxDepth(root.right)+1            if leftDep > rightDep:                return leftDep            else:                return rightDep

搞定!

自己又想写个不是递归的,怎能奈何10来分钟都没有思路。只能百度一下了。

啊,一看别人的代码。就是广度遍历不就好了。哎,还是太嫩了。这么简单的问题。

如下链接是原文:C++版

害怕丢失了,特记录在此:

class Solution {public:    //二叉树最大深度(层次遍历,遍历一层高度加1)    int maxDepth(TreeNode *root) {        int height = 0,rowCount = 1;        if(root == NULL){            return 0;        }        //创建队列        queue<treenode*> queue;        //添加根节点        queue.push(root);        //层次遍历        while(!queue.empty()){            //队列头元素            TreeNode *node = queue.front();            //出队列            queue.pop();            //一层的元素个数减1,一层遍历完高度加1            rowCount --;            if(node->left){                queue.push(node->left);            }            if(node->right){                queue.push(node->right);            }            //一层遍历完            if(rowCount == 0){                //高度加1                height++;                //下一层元素个数                rowCount = queue.size();            }        }        return height;    } };
自己还是太欠缺,慢慢来吧。多看多思考。老大说我做事有时候应该多思考,看来是没错啊。find the best way to do it


0 0
原创粉丝点击