【递归:代码】
C++:
class Solution {
public:
int TreeDepth(TreeNode* proot)
{
if(proot==NULL){
return 0;
}
return TreeDepth(proot->left)>TreeDepth(proot->right)?TreeDepth(proot->left)+1:TreeDepth(proot->right)+1;
}
};
Python:
class Solution:
def TreeDepth(self, proot):
if not proot:
return 0
return max(self.TreeDepth(proot.left),self.TreeDepth(proot.right))+1
【迭代:代码】
Python:
class Solution:
def TreeDepth(self, proot):
queue=[]
if not proot:
return 0
depth=1
queue.append((proot,depth))
while(queue):
head,depth=queue.pop(0)
if head.left:
queue.append((head.left,depth+1))
if head.right:
queue.append((head.right,depth+1))
return depth
C++:
待更新