【知识迁移能力】二叉树的深度

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ghscarecrow/article/details/82142820

此题出自牛客网的剑指offer专题

题目描述

输入一棵二叉树,求该树的深度。从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。

解题思路

对于这道题主要有两个思路

思路1:对于二叉树的遍历,不管是哪一个结点遍历的次序都是一样的,所以很明显可以使用递归写法,最后返回左子树和右子树的最大值即可

思路2:使用非递归写法,对二叉树进行层次遍历,利用循环不断更新二叉树的深度即可

实现代码

Java版本

//采用递归写法
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public int TreeDepth(TreeNode root) {
        if(root == null){
            return 0;
        }
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return left>right? left+1:right+1;
    }
}
//采用思路二非递归写法进行解题
import java.util.Queue;
import java.util.LinkedList;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    
    public int TreeDepth(TreeNode root) {
        if(root==null){
            return 0;
        }
        int depth=0;//记录深度
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while(queue.size()!=0){
            int len = queue.size();//记录下队列里面的元素个数
            depth++;//深度加一
            while(len-- != 0){
                TreeNode temp = queue.poll();//拿到队列头的第一个元素
                if(temp.left!=null) queue.add(temp.left);
                if(temp.right!=null) queue.add(temp.right);
            }
        }
        return depth;
    }
}

C++版本

//采用思路一的递归写法
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot == NULL){
            return 0;
        }
        int left = TreeDepth(pRoot->left);
        int right = TreeDepth(pRoot->right);
        return left>right? left+1:right+1;
    
    }
};
//采用思路二的非递归写法
/*
struct TreeNode {
	int val;
	struct TreeNode *left;
	struct TreeNode *right;
	TreeNode(int x) :
			val(x), left(NULL), right(NULL) {
	}
};*/
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        if(pRoot==NULL)
        {
            return 0;
        }
        int depth=0;
        queue<TreeNode*> q;
        q.push(pRoot);
        while(!q.empty())
        {
            int len = q.size();
            depth++;
            while(len--)
            {
                TreeNode* temp = q.front();
                q.pop();
                if(temp->left) q.push(temp->left);
                if(temp->right) q.push(temp->right);
            }
        }
        return depth;
    
    }
};

猜你喜欢

转载自blog.csdn.net/ghscarecrow/article/details/82142820