Height and depth of binary tree

I once knelt down on the side of JD.com's C++ intern, the interviewer said that the height of the binary tree, I actually wanted to use a formula to calculate it, could it be that I was crazy at that moment, after all, it was the first interview in my life, and the brain circuit was very strange It's not impossible to have it, but it can't be so strange, maybe it's a fool, okay, don't talk nonsense, let's go! The following codes are all codes passed by Niuke.com.

1. Recursive version (I have to say, recursion is really useful)

/*
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:right)+1;
    }
};

2. Non-recursive version (why the recursive version is simple and clear and there is a non-recursive version, of course, because recursion is time-consuming and space-consuming)

To put it bluntly, no matter which traversal method is used, the depth of the binary tree can be finally obtained, which is a good traversal method.

level-order traversal

 
 
class Solution {
public:
    int TreeDepth(TreeNode* pRoot)
    {
        queue<TreeNode *>q;
        if(pRoot==NULL)
            return 0;
        q.push(pRoot);
        int depth=0;
        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;
    }
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324613609&siteId=291194637