g*****g 发帖数: 212 | 1 int maxNode(Node *root, bool parentSet){
if(!root) return 0;
if (parentSet)
{
return maxNode(root->left, false) + maxNode(root->right, false);
}
else
{
int n1 = 1 + maxNode(root->left, true) + maxNode(root->right, true);
int n2 = maxNode(root->left, false) + maxNode(root->right, false);
return max(n1, n2);
}
} |
|
k******4 发帖数: 7 | 2 你想复杂了。这题不用看左右两个子树的返回值,只要一路DFS下去,看到比目前最大
值大的点,更新一下path就可以了。的确更新path是要O(LgN)的时间,在非最差情况下
可以忽略不计。
dfs(TreeNode* node, vector& path, int& maxNode, vector&
maxNodePath) {
path.push_back(node->val);
if (node->val > maxNode) {
maxNode = node->val;
maxNodePath = path;
}
if (node->left) dfs(node->left, path, maxNode, maxNodePath);
if (node->right) dfs(node->right, path, maxNode, maxNodePath);
path.pop_back();
} |
|
j**t 发帖数: 439 | 3 已经一天了,真的要疯掉了.好象是个很小的问题,可就是通不过.
double ent,dd;
Node* pHashList;
pCurSV=....; //此处略去
pHashList=pCurSV->hashList;
maxNodes=pCurSV->maxNodes;
for (i=0;i
{
ent=pHashList[i]->value; //value is a double
dd=ent+1;
printf("outcom =%f\n",i)
}
每次到i=5后,就出错.Segmentation Fault.
去掉dd=ent+1那一行, 则顺利通过.
真是奇怪极了.
OS is SunOS 5.7 Generic_106541-08 sun4u sparc SUNW,Ultra-60
可能和浮点运算有关.哪位大侠指点一下? |
|
l*****a 发帖数: 14598 | 4 u tried that?
真的没问题?
what is maxnode and maxnum with your code? |
|
c******0 发帖数: 260 | 5 我写了一下,不知道对不对。。。求指教
struct Node{
int val;
Node *left, *right;
Node(int v): val(v), left(NULL), right(NULL){}
};
void maxNodeHelp(Node *root, int &direct, int &undirect){
if(!root) return;
int nextDirect = 1, nextUndirect = 0;
maxNodeHelp(root->left, nextDirect, nextUndirect);
maxNodeHelp(root->right, nextDirect, nextUndirect);
direct += nextUndirect;
undirect += max(nextDirect, nextUndirect);
}
int maxNode(Node *root){
if(!root) return 0;
int di... 阅读全帖 |
|
l*******0 发帖数: 95 | 6 就是找后继节点呀
if node.right ! = null
return maxNode(node.right);
else
Node parent = node.parent;
while(parent.right == node) {
node = parent;
parent = node.parent;
}
return parent; |
|