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; }};
新闻热点
疑难解答