Day26-二叉树的最小深度
力扣链接
什么是最小深度,这个要理解一下:
-
从根节点 1 到叶子节点 4 的路径是
1 -> 2 -> 4
,路径长度为 3。 -
从根节点 1 到叶子节点 5 的路径是
1 -> 3 -> 5
,路径长度为 3。 -
从根节点 1 到叶子节点 6 的路径是
1 -> 3 -> 6
,路径长度为 3。
-
从根节点 1 到叶子节点 4 (左子树) 的路径是
1 -> 2 -> 4
,路径长度为 3。 -
从根节点 1 到叶子节点 4 (右子树) 的路径是
1 -> 3 -> 6 -> 4
,路径长度为 4。 -
从根节点 1 到叶子节点 5 的路径是
1 -> 3 -> 5
,路径长度为 3。
-
从根节点 1 到叶子节点 3 的路径是
1 -> 2 -> 3
,路径长度为 3。这个要注意一下不是1!
使用后序遍历+递归实现!
int GetDepth(struct TreeNode* root){if(root == NULL) return 0;int LeftDepth = GetDepth(root->left); // 左int RightDepth = GetDepth(root->right); //右if(root->left == NULL && root->right != NULL){ //重点需要理解的地方,如果左子树为空,但是右子树不为空return 1+RightDepth; //那么最低点应该在右子树的孩子里面}if(root->right == NULL && root->left != NULL){return 1+LeftDepth;} int result = 1 + (LeftDepth>RightDepth? RightDepth : LeftDepth);return result;}
int minDepth(struct TreeNode* root) {return GetDepth(root);
}
使用迭代法,层序遍历实现:
int minDepth(struct TreeNode* root) {if(root == NULL) return 0;int left = 0,right = 0,depth = 0;struct TreeNode* que[10000];que[right++] = root;while(left < right){int size = right - left;depth++; //每到一层就加1for(int i =0;i<size;i++){struct TreeNode* node = que[left++];if(node->left) que[right++] = node->left;if(node->right) que[right++] = node->right;if(node->left == NULL && node->right == NULL){return depth; //都遇到某一个节点是左右孩子为空的时候直接返回结果}}}return depth;
}
感觉模板还是挺耐用的,多动手练吧。