一、二叉樹是個搜索二叉樹node
二、二叉樹帶有指向parent的指針ide
可轉換成兩個鏈表的相交節點
spa
三、普通二叉樹指針
保存從根節點分別到這兩個節點的路徑到list1和list2中it
從list1和list2中找第一個不相等的節點即爲最近公共祖先節點ast
template<class T> BinaryTreeNode<T>* BinaryTree<T>::lastCommnParent(BinaryTreeNode<T>*& node1, BinaryTreeNode<T>*& node2) { if (_root == NULL || node1 == NULL || node2 == NULL)return NULL; std::list<BinaryTreeNode<T>*> list1, list2; GetNodePath(node1, list1); GetNodePath(node2, list2); BinaryTreeNode<T>* ret = _root; std::list<BinaryTreeNode<T>*>::iterator it1 = list1.begin(); std::list<BinaryTreeNode<T>*>::iterator it2 = list2.begin(); while (it1 != list1.end() && it2 != list2.end()){ if (*it1 == *it2){ ret = *it1; ++it1, ++it2; } else break; } return ret; } template<class T> void BinaryTree<T>::GetNodePath(BinaryTreeNode<T>*& node, std::list<BinaryTreeNode<T>*>& listpath) { if (node == NULL)return; BinaryTreeNode<T>* cur = _root; BinaryTreeNode<T>* prev = cur; listpath.push_back(cur); cur = cur->_leftchild; while (cur != NULL || !listpath.empty()){ while (cur != NULL){ listpath.push_back(cur); if (cur == node)return; cur = cur->_leftchild; prev = cur; } BinaryTreeNode<T>* top = listpath.back(); if (top->_rightchild == NULL || top->_rightchild == prev){ prev = top; listpath.pop_back(); } else cur = top->_rightchild; } }
《完》class