思路:二叉樹的深度等於左右子樹的最大深度加1,顯然利用遞迴。
**:
#include "stdafx.h"
#include #include using namespace std;
struct binarytreenode
;//求二叉樹的深度
int depth(binarytreenode *proot)
int nleftdepth = depth(proot->m_pleft);
int nrightdepth = depth(proot->m_pright);
return (nleftdepth > nrightdepth ? nleftdepth : nrightdepth) + 1;
}//以先序的方式構建二叉樹,輸入-1表示結點為空
void createbinarytree(binarytreenode *&proot)
else }
void printinorder(binarytreenode *&proot)
}int _tmain(int argc, _tchar* argv)
執行結果:
面試題39 1 二叉樹的深度
遞迴思想 如果一顆樹只有乙個節點,它的深度為1.如果根節點只有左子樹沒有右子樹,那麼它的深度為左子樹的深度加1,同理,只有右子樹沒有左子樹,它的深度為右子樹深度加1,如果既有左子樹又有右子樹,它的深度為左右子樹深度較大的加1。遞迴很容易實現 int findtreedeep bintree bt 非...
面試題55 二叉樹的深度
輸入一棵二叉樹的根結點,求該樹的深度。從根結點到葉結點依次經過的結點 含根 葉結點 形成樹的一條路徑,最長路徑的長度為樹的深度。例如下圖中的二叉樹的深度為4,因為它從根結點到葉結點最長的路徑包含4個結點 從根結點1開始,經過結點2和結點5,最終到達葉結點7 思路 如果一棵樹只有乙個結點,它的深度為1...
面試題55 二叉樹的深度
題目一 輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點 含根 葉結點 形成樹的一條路徑,最長路徑的長度為樹的深度。遞迴版本 class solution 非遞迴 層次遍歷 遞迴遍歷,僅僅一行 class solution 迭代版本 class solution return depth...