leetcode-111 Minimum Depth of Binary Tree
2015-04-06 15:44
295 查看
这题和104Maximum Depth of Binary Tree不一样,递归的时候不能直接返回min(left,right)+1
或者:
以上两种方法都是DFS(深度优先遍历),也可以采用广度优先遍历(BFS),当某个结点没有孩子节点时,就结束,当前的层数为树的最小深度
<span style="font-size:14px;">/** * 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 minDepth(TreeNode *root) { if(root == NULL) return 0; int left = minDepth(root->left); int right = minDepth(root->right); return (left == 0 || right == 0) ? left+right+1:min(left,right)+1; } };</span>
或者:
<span style="font-size:14px;">class Solution { public: int minDepth(TreeNode *root) { if(!root) return 0; if(!root->left) return 1 + minDepth(root->right); if(!root->right) return 1 + minDepth(root->left); return 1+min(minDepth(root->left),minDepth(root->right)); } };</span>
以上两种方法都是DFS(深度优先遍历),也可以采用广度优先遍历(BFS),当某个结点没有孩子节点时,就结束,当前的层数为树的最小深度
<span style="font-size:14px;">/** * 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 minDepth(TreeNode *root) { if(root == NULL) return 0; int level = 0; queue<TreeNode *> btn; btn.push(root); while(!btn.empty()){ level++; for(int i = 0,n = btn.size(); i < n; i++){ TreeNode *tmp = btn.front(); btn.pop(); if(!tmp->left && !tmp->right) return level;//某个节点没有孩子,则必为叶子节点 if(tmp->left) btn.push(tmp->left); if(tmp->right) btn.push(tmp->right); } } } };</span>
相关文章推荐
- Leetcode#111 Minimum Depth of Binary Tree
- leetCode #111 Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- leetcode 111 Minimum Depth of Binary Tree
- [LeetCode]111 Minimum Depth of Binary Tree
- LeetCode: Minimum Depth of Binary Tree [111]
- Leetcode[111]-Minimum Depth of Binary Tree
- Leetcode 111 Minimum Depth of Binary Tree
- leetcode[111]:Minimum Depth of Binary Tree
- [leetcode 111] Minimum Depth of Binary Tree
- leetcode_question_111 Minimum Depth of Binary Tree
- leetcode_111题——Minimum Depth of Binary Tree(二叉树,队列)
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- LeetCode(111)Minimum Depth of Binary Tree
- Leetcode_111_Minimum Depth of Binary Tree
- [Leetcode 111, Easy] Minimum Depth of Binary Tree
- 【LeetCode 111_二叉树_遍历】Minimum Depth of Binary Tree
- leetcode_question_111 Minimum Depth of Binary Tree
- LeetCode#111 Minimum Depth of Binary Tree
- [leetcode-111]Minimum Depth of Binary Tree(C语言)