[LeetCode-111] Minimum Depth of Binary Tree (二叉树最小深度)
2016-01-12 20:56
525 查看
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.
本题就是求解二叉树的深度:
递归解法:
(1)如果二叉树为空,二叉树的深度为0
(2)如果二叉树不为空,二叉树的深度 = min(左子树深度, 右子树深度) + 1
(3)需要注意的是斜二叉树情况,当节点的左子树深度为0或者节点的右子树深度为0.
采用DFS深度优先遍历,我们只要叶子节点。
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
本题就是求解二叉树的深度:
递归解法:
(1)如果二叉树为空,二叉树的深度为0
(2)如果二叉树不为空,二叉树的深度 = min(左子树深度, 右子树深度) + 1
(3)需要注意的是斜二叉树情况,当节点的左子树深度为0或者节点的右子树深度为0.
采用DFS深度优先遍历,我们只要叶子节点。
/** * Definition for a binary tree node. */ struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; }; int minDepth(TreeNode *root) { // Start typing your C/C++ solution below // DO NOT write int main() function if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 1; int leftDepth = minDepth(root->left); int rightDepth = minDepth(root->right); if (leftDepth == 0) return rightDepth + 1; else if (rightDepth == 0) return leftDepth + 1; else return leftDepth < rightDepth ? (leftDepth +1 ) : (rightDepth +1); }
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解