leetcode104二叉树搜索

  1. 深度优先搜索,递归
maxDepth(TreeNode* root){
  if(!root)return 0;
  return max(maxDepth(root->left),maxDepth(root->right))+1;    
}

 

  1. 广度优先搜索,队列
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
  int size=q.size();
  while(size>0){
     TreeNode* node=q.front();q.pop();
      if(node->left)q.push(node->left);
      if(node->right)q.push(node->right);  
      size--;
  }
  //一层遍历结束
  ans++;       
}    

 

posted @ 2023-07-18 13:53  iu本u  阅读(9)  评论(0)    收藏  举报