Depth prove safety office- binary tree - cattle off network

Title: Enter a binary tree, find the depth of the tree. Forming a path tree from the root node to the leaf node sequentially passes (including the root, leaf nodes), the depth of the length of the longest path in the tree.
Ideas: recursion.

/*
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;
        return max(TreeDepth(pRoot->left)+1,TreeDepth(pRoot->right)+1);
    
    }
};

python:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def TreeDepth(self, pRoot):
        # write code here
        if(pRoot==None):
            return 0
        left = self.TreeDepth(pRoot.left)
        right=self.TreeDepth(pRoot.right)
        if left >right:
            return left+1
        else:
            return right+1

Guess you like

Origin blog.csdn.net/qq_43387999/article/details/91126739