Binary tree depth (28)

topic

[Input binary tree, find the depth of the tree. From the root node to a leaf node sequentially passes (including the root, leaf node) tree forming a path, the length of the longest path depth of the tree]


1, analysis

  • The depth of the binary tree for a depth of about 1 plus each subtree (if present around subtree), and then processed recursively.
    2, the code
/*
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==nullptr)
            return 0;
        int leftCount = TreeDepth(pRoot->left);
        int rightCount = TreeDepth(pRoot->right);
        return (leftCount>rightCount)?(leftCount+1):(rightCount+1);
    
    }
};
Published 213 original articles · won praise 48 · views 110 000 +

Guess you like

Origin blog.csdn.net/Jeffxu_lib/article/details/104886084