求一颗二叉树的最大深度.
方法1:
层次遍历法,bfs,利用队列先进先出的思想.
方法2:
递归法,dfs
Java实现
import java.util.LinkedList;
import java.util.Queue;
class TreeNode{
private int val;
public TreeNode left;
public TreeNode right;
TreeNode(){}
TreeNode(int val){this.val=val;}
TreeNode(int val,TreeNode left,TreeNode right){
this.val=val;
this.left=left;
this.right=right;
}
}
public class maxDepth {
public int MaxDepthOfTree(TreeNode root){
int count=0,n=0;
Queue<TreeNode> node=new LinkedList<>();
node.add(root);
while(!node.isEmpty()){
n=node.size();
while(n-->0){
if(node.peek().left!=null){
node.add(node.peek().left);
}
if(node.peek().right!=null){
node.add(node.peek().right);
}
node.poll();
}
count++;
}
return count;
}
public static void main(String[] args){
TreeNode r21=new TreeNode(15);
TreeNode r22=new TreeNode(7);
TreeNode l1=new TreeNode(9);
TreeNode r1=new TreeNode(20,r21,r22);
TreeNode root=new TreeNode(3,l1,r1);
System.out.println(new maxDepth().MaxDepthOfTree(root));
}
}
C++实现
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
struct TreeNode{
private:
int val;
public:
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(nullptr),right(nullptr){}
};
class Solution{
public:
int maxDepth(TreeNode* root){
return root?1+max(maxDepth(root->left),maxDepth(root->right)):0;
}
int bfsDepth(TreeNode* root){
queue<TreeNode*> node{{root}};
int count=0,n=1;
while(!node.empty()){
n=node.size();
for(int i=0;i<n;i++){
if(node.front()->left!=nullptr){
node.push(node.back()->left);
}
if(node.front()->right!=nullptr){
node.push(node.front()->right);
}
node.pop();
}
count++;
}
return count;
}
};
int main(int argc,char* argv[]){
TreeNode root(3);
TreeNode ln1(9);
TreeNode rn1(20);
TreeNode rn21(15);
TreeNode rn22(7);
root.left=&ln1;
root.right=&rn1;
rn1.left=&rn21;
rn1.right=&rn22;
cout<<Solution().bfsDepth(&root)<<endl;
return 0;
}