题目:
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:设置一个变量存储当前记录下的最小深度,采用先序遍历的方法访问树的每一个节点,设置一个变量表示当前节点所在的层次,如果一个节点没有子节点,那么就比较该节点的深度与当前的最小深度,选择两者之中较小的作为当前的最小深度。
代码:
/** * 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) { int curr_depth=0,min_depth=1000000; return PreorderTraverse(root,&curr_depth,min_depth); } private: int PreorderTraverse(TreeNode *root, int *curr_depth, int min_depth){ if(root==nullptr)return 0; (*curr_depth)++; if(root->left!=nullptr){ min_depth=PreorderTraverse(root->left, curr_depth, min_depth); } if(root->right!=nullptr){ min_depth=PreorderTraverse(root->right, curr_depth, min_depth); } if((root->left==nullptr)&&(root->right==nullptr)){ min_depth=min(*curr_depth,min_depth); } (*curr_depth)--; return min_depth; } };
解题思路2:另一种思路是,当节点为空时,判断其是否有兄弟节点,如果没有,那么令该节点的深度为0,如果有兄弟节点,令该节点的深度为正无穷(INT_MAX)。这样一来,在上一层节点进行选择时,将选择该节点的兄弟节点的深度作为子节点的深度。
代码2:
/** * 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) { return minDepth(root,false); } private: int minDepth(TreeNode *root, bool hasbrother){ if(!root){ return hasbrother==false?0:INT_MAX; } return 1+min(minDepth(root->left,root->right!=NULL),minDepth(root->right,root->left!=NULL)); } };