[Leetcode]-Minimum Depth of Binary Tree
2017-06-28 08:55
267 查看
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.
Hide Tags :Tree , Depth-first Search
题目:求取二叉树中最小深度,根节点定义为1深度。
思路:相同採取递归
递归终止条件:
A:假设root为NULL。说明已经越界,返回深度0
推断节点走向:
A:假设root为树叶, if(root->left == NULL && root->right == NULL) 返回深度1
B:假设节点无左节点,即if(root->left == NULL ) ,则运行递归return minDepth(root->right) + 1;
C:假设节点无右节点,则return minDepth(root->left ) + 1;
递归主进程:
int l = minDepth(root->left) + 1 ;
int r = minDepth(root->right)+ 1 ;
最后在推断l与r的大小,返回小者return min(l,r);
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Hide Tags :Tree , Depth-first Search
题目:求取二叉树中最小深度,根节点定义为1深度。
思路:相同採取递归
递归终止条件:
A:假设root为NULL。说明已经越界,返回深度0
推断节点走向:
A:假设root为树叶, if(root->left == NULL && root->right == NULL) 返回深度1
B:假设节点无左节点,即if(root->left == NULL ) ,则运行递归return minDepth(root->right) + 1;
C:假设节点无右节点,则return minDepth(root->left ) + 1;
递归主进程:
int l = minDepth(root->left) + 1 ;
int r = minDepth(root->right)+ 1 ;
最后在推断l与r的大小,返回小者return min(l,r);
/** * Definition for a binary tree node. * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ #define min(a,b) (((a)<(b))?(a):(b)) int minDepth(struct TreeNode* root) { if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return 1; else if(root->left == NULL ) return minDepth(root->right) + 1; else if(root->right== NULL ) return minDepth(root->left ) + 1; int l = minDepth(root->left) + 1 ; int r = minDepth(root->right)+ 1 ; return min(l,r); }
相关文章推荐
- [面试真题] LeetCode:Minimum Depth of Binary Tree
- LeetCode:Minimum Depth of Binary Tree
- [leetcode刷题系列]Minimum Depth of Binary Tree
- LeetCode: Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- [Leetcode] Minimum Depth of Binary Tree
- leetcode 31: Minimum Depth of Binary Tree
- leetcode--Minimum Depth of Binary Tree
- [LeetCode] Minimum Depth of Binary Tree - BFS
- LeetCode-Minimum Depth of Binary Tree
- 【LeetCode with Python】 Minimum Depth of Binary Tree
- [leetcode]Minimum Depth of Binary Tree
- Leetcode: Minimum Depth of Binary Tree
- [LeetCode 111] - 二叉树的最小深度 (Minimum Depth of Binary Tree)
- leetcode: Minimum Depth of Binary Tree
- 【leetcode】Minimum Depth of Binary Tree
- [LeetCode]Minimum Depth of Binary Tree
- LeetCode_Minimum Depth of Binary Tree
- LeetCode题目笔记(一) -- Minimum Depth Of Binary Tree
- leetcode -- Minimum Depth of Binary Tree