木落长安rr

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Note: A leaf is a node with no children.

Example:

Given binary tree [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
return its depth = 3

方法一:采用递归方法:(C++)

①如果一棵树只有一个结点,它的深度为1。

②如果根结点只有左子树而没有右子树,那么树的深度应该是其左子树的深度加1;同样如果根结点只有右子树而没有左子树,那么树的深度应该是其右子树的深度加1。

③如果既有右子树又有左子树,那该树的深度就是其左、右子树深度的较大值再加1。

1 int maxDepth(TreeNode* root) {
2         if(!root)
3             return 0;
4         int nleft=maxDepth(root->left);
5         int nright=maxDepth(root->right);
6         return nleft>nright?nleft+1:nright+1;
7     }

Java:

1 public int maxDepth(TreeNode root) {
2         if(root==null)
3             return 0;
4         int nleft=maxDepth(root.left);
5         int nright=maxDepth(root.right);
6         return nleft>nright?nleft+1:nright+1;
7     }

方法二:采用迭代方法:利用队列先进先出的特性,将每一层的结点弹出后,再将其左右子树压进队列,直至该层的结点全部弹出(C++)

 1 int maxDepth(TreeNode* root) {
 2         if(!root)
 3             return 0;
 4         int res=0;
 5         queue<TreeNode*> q;
 6         q.push(root);
 7         while(!q.empty()){
 8             res++;
 9             for(int i=q.size();i>0;i--){
10                 TreeNode* t=q.front();
11                 q.pop();
12                 if(t->left)
13                     q.push(t->left);
14                 if(t->right)
15                     q.push(t->right);
16             }
17         }
18         return res;
19     }

Java:

 1 public int maxDepth(TreeNode root) {
 2         if(root==null)
 3             return 0;
 4         Queue<TreeNode> m=new LinkedList<>();
 5         m.offer(root);
 6         int res=0;
 7         while(!m.isEmpty()){
 8             res++;
 9             for(int i=m.size();i>0;i--){
10                 TreeNode t=m.poll();
11                 if(t.left!=null)
12                     m.offer(t.left);
13                 if(t.right!=null)
14                     m.offer(t.right);
15             }
16         }
17         return res;
18     }

 

posted on 2019-04-02 10:57  木落长安rr  阅读(162)  评论(0编辑  收藏  举报