面试题50_找到一条路径
很多题目都可以抽象出来这道题目,该题目的要求就是找到目的路径之后就尽快返回,不要再继续遍历下去。
注:
if(!found)
path.pop_back();
只有在左右子树都没有发现目标节点的时候才弹出。如果想要保存path 并在函数以外使用,必须加上这句,因为没有在这句判断语句的话,函数的回溯过程不会弹出path 中的结点。
//面试题50
//给定一棵二叉树和其中一个叶子节点,输出根节点到指定叶子节点的之间的路径
// 10
// / \
// 5 12
// / \
// 4 7
//指定节点7,则输出10,5,7
#include<iostream>
#include<list>
using namespace std;
class BiTree
{
public:
int value;
BiTree *pLeft;
BiTree *pRight;
BiTree(int x):value(x),pLeft(nullptr),pRight(nullptr) {}
};
bool GetNodePath(BiTree *pRoot, BiTree *pNode, list<BiTree *> path)
{
if(pRoot==nullptr || pNode==nullptr)
return false;
path.push_back(pRoot);
bool found=false;
if(pRoot==pNode)
{
found=true;
for(auto mem:path)
cout<<mem<<" ";
return found;
}
if(!found && pRoot->pLeft)
found=GetNodePath(pRoot->pLeft,pNode,path);
if(!found && pRoot->pRight)
found=GetNodePath(pRoot->pRight,pNode,path);
if(!found)
path.pop_back();
return found;
}