关于这道题,可以将其转化为求两个单链表的第一个焦点,这种做法需要两个栈,分别存储根节点到给定节点的路径。
下面给出新的解法,利用后根遍历,代码如下:
bool findCommonFather(treenode *root, char a, char b) //a不一定是左节点,b不一定是右节点 { bool left = false, right = false; if(root->lchild != NULL) { left = findCommonFather(root->lchild, a, b); } if(root->rchild != NULL) { right = findCommonFather(root->rchild, a, b); } if(root->data == a) { if(left) { right = true; } else { left = true; } } else if(root->data == b) { if(right) { left = true; } else { right = true; } } if(left && right) { cout<<root->data<<endl; } return left || right; }