[LeetCode] Minimum Depth of Binary Tree

来源:互联网 发布:书籍印刷排版软件 编辑:程序博客网 时间:2024/06/05 17:58
int minDepth(TreeNode *root) {vector<TreeNode*> nodes;vector<int> depths;int min_depth = 0;if(root != NULL){nodes.push_back(root);depths.push_back(1);}while(!nodes.empty()){TreeNode* cur_node = nodes.back();int cur_node_depth = depths.back();TreeNode* left_child  = cur_node->left;TreeNode* right_child = cur_node->right;nodes.pop_back();depths.pop_back();if(right_child != NULL){nodes.push_back(right_child);int right_child_depth = cur_node_depth + 1;depths.push_back(right_child_depth);}if(left_child != NULL){nodes.push_back(left_child);int left_child_depth = cur_node_depth + 1;depths.push_back(left_child_depth);}if(left_child == NULL && right_child == NULL){if(min_depth == 0){min_depth = cur_node_depth;}else if(cur_node_depth < min_depth){min_depth = cur_node_depth;}            }}return min_depth;}
参考Binary Tree Postorder Traversal遍历方法
0 0
原创粉丝点击