返回n- tree中最大值节点



我正在尝试求解n-nary tree的"最大值节点"。问题,但是当最大节点出现在树的最低层的最右边位置时,我得到了超过时间限制的错误。

返回树节点指针的函数:

TreeNode<int>* maxDataNode(TreeNode<int>* root) {
if(root == NULL){
return root;
}
TreeNode<int>* max;
max = root;
for(int i =0;i < root->children.size();i++){
if(maxDataNode(root->children[i])->data > max->data ){
max=maxDataNode(root->children[i]);
}
}
return max;
}

避免使用相同的参数两次调用maxDataNode:

TreeNode<int>* maxDataNode(TreeNode<int>* root) {
if(root == NULL){
return NULL;
}
TreeNode<int>* max;
max = root;
for(int i =0;i < root->children.size();i++){
TreeNode<int> *curr = maxDataNode(root->children[i]);
if(curr->data > max->data ){
max=curr;
}
}
return max;
}

最新更新