Minimum Depth of Binary Tree (leetcode)

来源:互联网 发布:如何选冰箱 知乎 编辑:程序博客网 时间:2024/05/16 10:25

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.


https://oj.leetcode.com/problems/minimum-depth-of-binary-tree/


使用二叉树非递归后续遍历得到从根节点到叶子节点的最小长度。


/** * 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) {if (!root) {return 0;}std::stack<TreeNode *> mystack;bool is_node_visited = false;TreeNode *curr = root;TreeNode *prev_visited = NULL;int min_depth = 0;int curr_depth = 0;do {while (curr && !is_node_visited) {mystack.push(curr);++curr_depth;curr = curr->left;}curr = mystack.top();if (curr->right && curr->right != prev_visited) {curr = curr->right;is_node_visited = false;} else {//it's the leaf node, get the depth;if (!curr->left && !curr->right) {if (min_depth == 0) {min_depth = curr_depth;} else {min_depth = std::min(min_depth, curr_depth);}}prev_visited = curr;is_node_visited = true;mystack.pop();--curr_depth;}} while (!mystack.empty());return min_depth;    }};


0 0
原创粉丝点击