【Minimum Depth of Binary Tree】

xiaoxiao2021-02-28  84

题目:

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.

题意:求最小路径。

方法一:递归

class Solution { public: int run(TreeNode* root) { if (root==NULL) { return 0; } int left = run(root->left); int right = run(root->right); return 1 + min(left,right); } }; 方法二:非递归,采用层次遍历,如果该层有叶子节点,那么最短depth到此为止,如果没有,继续遍历下一层

class Solution { public: int run(TreeNode* root) { if(root==NULL) { return 0; } if (root->left == NULL && root->right == NULL) { return 1; } int depth = 0; queue<TreeNode*> qu; qu.push(root); while (!qu.empty()) { int len = qu.size(); depth++; for (int i = 0; i<len; i++) { TreeNode* cur = qu.front(); qu.pop(); if (cur->left == NULL && cur->right == NULL) { return depth; } if (cur->left != NULL) { qu.push(cur->left); } if (cur->right != NULL) { qu.push(cur->right); } } } } };

转载请注明原文地址: https://www.6miu.com/read-80167.html

最新回复(0)