首页 > 学院 > 开发设计 > 正文

minimum-depth-of-binary-tree

2019-11-08 01:10:03
字体:
来源:转载
供稿:网友
题目描述

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

IDEA

求树的最小深度:

1.递归 先序遍历 (深度优先)

2.层序遍历(广度优先)

CODE

1.

class Solution {public:    int run(TreeNode *root) {        if(root==NULL)            return 0;        int left_depth=run(root->left);        int right_depth=run(root->right);        if(left_depth==0||right_depth==0)            return 1+left_depth+right_depth;        return 1+min(left_depth,right_depth);    }};2.

class Solution {public:    int run(TreeNode *root) {        if(root==NULL)            return 0;        int level=0;        queue<TreeNode*> que;        que.push(root);        while(!que.empty()){            int size=que.size();            level++;            while(size--){                TreeNode *p=que.front();                que.pop();                if(p->left==NULL&&p->right==NULL)                    return level;                if(p->left){                    que.push(p->left);                }	                if(p->right){                    que.push(p->right);                }               }        }        return level;    }};


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表