1. 程式人生 > >查詢二叉樹的指定節點及根節點到該節點的路徑

查詢二叉樹的指定節點及根節點到該節點的路徑

//查詢二叉樹指定節點
bool hasNode(TreeNode* pRoot, TreeNode* pNode){
    if(pRoot == pNode)
        return true;
    bool has = false;
    if(pRoot->lchild != NULL)
        has = hasNode(pRoot->lchild, pNode);
    if(!has && pRoot->rchild != NULL){
        has = hasNode(pRoot->rchild, pNode);
    }
    return has;
}

//利用了後序遍歷的思想
//後續搜尋每條路徑,並將每條路徑經過的節點壓棧
//當此路徑上無要找尋的節點時,將此路徑上的節點依次退棧
bool GetNodePath(TreeNode *pRoot, TreeNode *pNode, stack<TreeNode*> &path){
    if(pRoot == pNode)
        return true;
    //不存在此節點
    if(hasNode(pRoot, pNode) == false)
        return false;
    //先將當前節點入棧
    path.push(pRoot);
    bool found = false;
    if(pRoot->lchild != NULL)
        found = GetNodePath(pRoot->lchild, pNode, path);
    if(!found && pRoot->rchild != NULL)
        found = GetNodePath(pRoot->rchild, pNode, path);
    //如果此路徑沒有找到,出棧
    if(!found)
        path.pop();
    return found;
}