题解 | #二叉树的深度#

二叉树的深度

https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=265&rp=1&ru=%2Fexam%2Foj%2Fta&qru=%2Fexam%2Foj%2Fta&sourceUrl=%2Fexam%2Foj%2Fta%3FjudgeStatus%3D3%26page%3D1%26pageSize%3D50%26search%3D%26tpId%3D13%26type%3D265&difficulty=&judgeStatus=3&tags=&title=&gioEnter=menu

/*
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) {
      int res = 0;
      int tmp = 0;
      
      curision(pRoot, res, tmp);
      
      return res;
    }
  private:
    void curision(TreeNode *root, int &res, int &tmp) {
      if (root == nullptr) {
        res = std::max(res, tmp);
        return ;
      }
      
      ++tmp;
      curision(root->left, res, tmp);
      curision(root->right, res, tmp);
      //  回溯
      --tmp;
    }
};

简洁

/*
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;
      }
      
      //  1是当前节点,加上左右子树中最大的那部分
      return 1 + std::max(TreeDepth(pRoot->left), TreeDepth(pRoot->right));
    }
};
全部评论

相关推荐

2025-12-18 11:59
广州南方学院 C++
牛客78682892...:直接点还好,总比要了简历也不回的强
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务