二叉樹深度(Depth)`遞迴`與`非遞迴`
阿新 • • 發佈:2018-12-08
二叉樹 (`Depth`)遞迴 深度優先遍歷 DFS
二叉樹的高度(深度)為二叉樹結點層次的最大值,也可以認為在根節點不為 nullptr 的情況下左右子樹的最大高度 + 1;
先序(後序)遍歷求解二叉樹高度(Depth)的遞迴演算法
演算法描述:深度優先遍歷
若 root 為空,則 Depth 為 0
若 root 非空,則 Depth 為左右子樹的最大高度 + 1
程式碼如下
class Solution { public: int maxDepth(TreeNode* root) { if(root == nullptr) //root 為空,高度(Depth)為 0 return 0; int depth_left, depth_right, depth_max; depth_left = maxDepth(root->left); //遍歷左子樹 depth_right = maxDepth(root->right); //遍歷右子樹 depth_max = depth_left > depth_right ? depth_left : depth_right; return (depth_max + 1); } };
int g_max_depth = 0;
void maxDepth(TreeNode* root, int _depth)
{
if(root != nullptr)
{
if(_depth > g_max_depth)
g_max_depth = _depth; //如果當前結點的層次值大於 depth ,更新 depth 值
maxDepth(root->left, _depth + 1);
maxDepth(root->right, _depth + 1);
}
}
演算法思想
二叉樹的高度(Depth)為二叉樹中結點層次的最大值,假設根結點為第一層結點,左右 h 層的結點的左右孩子都在 h + 1 層,因此可以通過遍歷計算二叉樹中的沒個結點的層次,其中最大值為二叉樹的高度(Depth)
二叉樹 (`Depth`)非遞迴 廣度優先遍歷 BFS
廣度優先遍歷又叫層次遍歷,從根結點開始,每遍歷完一層 Depth + 1,直到最後一層;基於佇列實現;當且僅當二叉樹的每一層結點出隊完畢 Depth + 1;
演算法描述
利用佇列進行二叉樹高度(Depth)計算的非遞迴寫法
若 root 為空,則返回 0 值
每次只有把同一層的結點輸出,則 Depth + 1,因此要知道當前佇列的長度 int length = q.size();當前佇列的長度就是這一層的結點數
每一層的結點 pop 出隊
TreeNode* pRoot = root;
while(length--)
{
pRoot = q.front();
q.pop();
if(root->left != nullptr)
q.pop(pRoot->left);
if(root->right != nullptr)
q.pop(pRoot->right);
}
程式碼如下
int maxDepth(TreeNode* root)//利用佇列進行非遞迴演算法
{
queue<TreeNode*> q;
TreeNode* pRoot=root;
int _depth=0,lenth;
if(root == nullptr)
return 0;
q.push(pRoot);
while(!q.empty())//每次只有把在同一層的所有結點出隊以後才_depth++,因此要知道當前佇列的長度,用lenth表示
{
_depth++;
lenth=q.size();//當前佇列長度就代表這一層的結點個數
while(lenth--)
{
pRoot=q.front();
q.push();
if(pRoot->left)
q.push(pRoot->left);
if(pRoot->right)
q.push(pRoot->right);
}
}
return _depth;
}