题解 | #二叉树的深度#
二叉树的深度
https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ #include <queue> class Solution { public: // dfs int visit_dfs(TreeNode* root) { if (!root) { return 0; } int l = visit_dfs(root->left); int r = visit_dfs(root->right); // std::cout << l << " " << r << std::endl; return max(l, r) + 1; // ->xx,非空,则表示层数 +1 } // 层序遍历,利用队列的先进先出的性质 int visit_seq(TreeNode* root) { if (!root) return 0; queue<TreeNode*> q; int res = 0; // 记录层数 q.push(root); while (!q.empty()) { int n = q.size(); for(int i = 0; i < n; ++i) { TreeNode* tmp = q.front(); // 存储下一层的节点 if (tmp->left) { q.push(tmp->left); } if(tmp->right) { q.push(tmp->right); } q.pop(); // 把当前层的节点出队 } ++res; // 层数增加 } return res; } int TreeDepth(TreeNode* pRoot) { TreeNode* root = pRoot; // dfs int num = 0; // num = visit_dfs(root); num = visit_seq(root); return num; } };
挤挤刷刷! 文章被收录于专栏
记录coding过程