给定一个二叉树,求此二叉树的深度。
递归方法:
int TreeDepth(TreeNode* pRoot) { if (pRoot == NULL) return 0; if (pRoot->left == NULL && pRoot->right == NULL) return 1; return max(TreeDepth(pRoot->left), TreeDepth(pRoot->right)) + 1; }非递归方法:广度遍历思想
int TreeDepth(TreeNode* pRoot) { if (pRoot == NULL) return 0; queue<TreeNode *> q; q.push(pRoot); int res = 0; while (!q.empty()) { int size = q.size(); for (int i = 0; i < size; ++i) { TreeNode *tmp = q.front(); q.pop(); if (tmp->left) { q.push(tmp->left); } if (tmp->right) { q.push(tmp->right); } } res++; } return res; }