二叉树的最大深度

104 二叉树的最大深度

书上的递归法解决(C++)

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        TreeNode* cur = root;
        if(cur == NULL){
            return 0;
        }
        else{
            int i = maxDepth(cur->left);
            int j = maxDepth(cur->right);
            return (i<j)?j+1:i+1;
        }
    }
};

 

由这个题我首先想到的是前几天的层序遍历,把每一层的放在一个链表里面,这个题计算深度就直接统计层数就可以了。

java代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int maxDepth(TreeNode root) {
        if(root == null) return 0;
        Queue<TreeNode> que = new LinkedList<>();
        que.offer(root);
        int count = 0,level = 0;
        TreeNode cur = null;
        while(!que.isEmpty()){
            count = que.size();
            level++;
            while(count>=1){
                cur = que.poll();
                if(cur.left != null){
                    que.offer(cur.left);
                }
                if(cur.right != null){
                    que.offer(cur.right);
                }
                count--;
            }
        }
        return level;
    }
}

C++代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxDepth(TreeNode* root) {
        if(root==NULL){//首先判断根节点是否为空
            return 0;
        }
        int level = 0;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int count = q.size();
            level++;
            while(count > 0){
                TreeNode* cur = q.front();
                
                q.pop();
                
                if(cur->left != NULL){
                    q.push(cur->left);
                }
                if(cur->right != NULL){
                    q.push(cur->right);
                }
                count--;
            }
        }
        return level;
    }
};
posted @ 2019-05-14 23:04  +D  阅读(280)  评论(0编辑  收藏  举报