/* 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 len=0; if(pRoot==NULL) return 0; while(pRoot->val) { len++; pRoot=pRoot->left; } return len; } };
不通过
您的代码已保存
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
递归思路!
/* 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 len=0; if(pRoot==NULL) return 0; return max(1+TreeDepth(pRoot->left), 1+TreeDepth(pRoot->right)); } };
//由于每个节点都需要判断下面左右节点是不是存在,若存在则要继续递归往下判断。所有需要调用两次本体函数
//一个摸左边,一个摸右边。 但是每次摸完,我们要的是最深的,所以我们返回左右两边最大的那个值。
//那么值是怎么来的? 递归是有外向内,再由内向外。 这里由上到下,再由下到上。一步一步上去,每递归一次,层数加1.则最下面返回0就好了
bfs的解法 思路新颖巧妙。层序遍历到最深!
int TreeDepth(TreeNode* pRoot) { queue<TreeNode*> q; if(!pRoot) return 0; q.push(pRoot); int level=0; while(!q.empty()){ int len=q.size(); level++; while(len--){ TreeNode* tem=q.front(); q.pop(); if(tem->left) q.push(tem->left); if(tem->right) q.push(tem->right); } } return level; }