- 采用后序遍历+栈的方式进行实现:
- 算法思路:若当前结点的值为题目中要找的x,那么此时栈里面的所有元素都是其祖先;否则,继续进行后序遍历。
void printAllAncestor(TreeNode *root, int x){
if (root == NULL)
return;
TreeNode *cur = root;
TreeNode *prev = NULL;
stack<TreeNode*> st;
while (cur != NULL || !st.empty()){
while (cur != NULL){
st.push(cur);
cur = cur->left;
}
cur = st.top();
if (cur->val == x){
st.pop();
while (!st.empty()){
printf("%d ", st.top()->val);
st.pop();
}
}
else if (cur->right == NULL || cur->right == prev){
st.pop();
prev = cur;
cur = NULL;
}
else{
cur = cur->right;
}
}
}