二元树中和为某一值的全部路径

二元树中和为某一值的全部路径

大家好,又见面了,我是全栈君,祝每个程序员都可以多学几门语言。

             近期在这里看到一道面试题,看了题目和作者的解答后,感觉真是强大。

     题目:输入一个整数和一棵二元树。从树的根结点開始往下訪问一直到叶结点所经过的全部结点形成一条路径。打印出和与输入整数相等的全部路径。

     比如输入整数22和例如以下二元树

                                      二元树中和为某一值的全部路径

    则打印出两条路径:10, 12和10, 5, 7。

    二元树结点的数据结构定义为:

struct BinaryTreeNode // a node in the binary tree
{
      int              m_nValue; // value of node
      BinaryTreeNode  *m_pLeft;  // left child of node
      BinaryTreeNode  *m_pRight; // right child of node
};

        作者的解答为:

///////////////////////////////////////////////////////////////////////// Find paths whose sum equal to expected sum///////////////////////////////////////////////////////////////////////void FindPath(      BinaryTreeNode*   pTreeNode,    // a node of binary tree      int               expectedSum,  // the expected sum      std::vector<int>& path,         // a path from root to current node      int&              currentSum    // the sum of path){      if(!pTreeNode)            return;      currentSum += pTreeNode->m_nValue;      path.push_back(pTreeNode->m_nValue);      // if the node is a leaf, and the sum is same as pre-defined,       // the path is what we want. print the path      bool isLeaf = (!pTreeNode->m_pLeft && !pTreeNode->m_pRight);      if(currentSum == expectedSum && isLeaf)      {               std::vector<int>::iterator iter = path.begin();           for(; iter != path.end(); ++ iter)                 std::cout << *iter << '\t';           std::cout << std::endl;      }      // if the node is not a leaf, goto its children      if(pTreeNode->m_pLeft)            FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);      if(pTreeNode->m_pRight)            FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);      // when we finish visiting a node and return to its parent node,      // we should delete this node from the path and       // minus the node's value from the current sum      currentSum -= pTreeNode->m_nValue;      path.pop_back();} 

      细致看代码,你会发现,这样的方法遍历了解空间树,全部的叶子节点都会訪问到,

        假设二叉树是这种呢:

        二元树中和为某一值的全部路径

       依照这样的方法,20的两个孩子都会訪问到,可是,这在做无用功,由于,题目要求的是从根节点到叶子节点的路径和为22,当訪问到20的时候,路径和已是30了(大于22),再訪问20的孩子,路径和也会大于22,这样就没有必要再訪问20的孩子了。

       所以,应该避免这样的无效搜索,在遍历每一个节点的时候,先推断路径和是否大于目标值,假设大于的话,则不要遍历该节点的孩子,而且回溯。

      优化后的代码为:

void FindPath(	 BinaryTreeNode* pTreeNode, // a node of binary tree	 int expectedSum, // the expected sum	 std::vector<int>& path, // a path from root to current node	 int& currentSum // the sum of path	 ){	if(!pTreeNode)		return;	currentSum += pTreeNode->m_nValue;	if(currentSum > expectedSum){  //推断路径和是否会超出目标值,超出则回溯		currentSum -= pTreeNode->m_nValue;		return;	}	path.push_back(pTreeNode->m_nValue);		// if the node is a leaf, and the sum is same as pre-defined,		// the path is what we want. print the path	bool isLeaf = (!pTreeNode->m_pLeft && !pTreeNode->m_pRight);	if(currentSum == expectedSum && isLeaf)	{		std::vector<int>::iterator iter = path.begin();		for(; iter != path.end(); ++ iter)		std::cout << *iter << '\t';		std::cout << std::endl;	}	// if the node is not a leaf, goto its children	if(pTreeNode->m_pLeft)		FindPath(pTreeNode->m_pLeft, expectedSum, path, currentSum);	if(pTreeNode->m_pRight)		FindPath(pTreeNode->m_pRight, expectedSum, path, currentSum);	// when we finish visiting a node and return to its parent node,	// we should delete this node from the path and	// minus the node's value from the current sum	currentSum -= pTreeNode->m_nValue;	path.pop_back();}

        在原来的代码里添加�了例如以下代码:

if(currentSum > expectedSum){  //推断路径和是否会超出目标值,超出则回溯		currentSum -= pTreeNode->m_nValue;		return;	}

        剪去无效的子树,避免无效搜素,提高效率。

參考:

http://zhedahht.blog.163.com/blog/static/254111742007228357325/

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/118895.html原文链接:https://javaforall.net

(0)
上一篇 2021年11月29日 下午5:00
下一篇 2021年11月29日 下午6:00


相关推荐

  • 代理模式的使用总结

    代理模式的使用总结目录一、代理模式二、静态代理(一)静态代理(二)静态代理简单实现三、动态代理(一)动态代理(二)动态代理简单实现四、动态代理原理分析五、InvocationHandler接口和Proxy类详解六、JDK动态代理和CGLIB动态代理代码示例比较与总结(一)定义创建用户管理接口(二)用户管理实现类,实现用户管理接口(被代理的实现类)(三)采用JDK代…

    2022年4月27日
    34
  • hdu5188 加限制的01背包问题「建议收藏」

    hdu5188 加限制的01背包问题

    2022年1月27日
    44
  • Pycharm自动导入模块小技巧「建议收藏」

    Pycharm自动导入模块小技巧「建议收藏」周末愉快!不知道大家周末写不写代码,哈哈,反正我已经加完班回来了,今天分享一个能提高编码效率的小技巧,可能你早就在用了,也可能像我一样刚学会,还是趁热跟大家分享一下。如果能把工具熟练运用,往往能达到事半功倍的效果,Pycharm是很多Python开发者的首选IDE,提供各种快捷键、重构功能、调试技巧等,Python是动态语言,对于自动导入模块没有静态语言那么方便,但有了Pycharm,还是…

    2022年8月27日
    6
  • Windows编译ollvm_windows交叉编译linux

    Windows编译ollvm_windows交叉编译linux听过Mozilla(火狐浏览器的娘家)的javascript引擎吗?感兴趣吗?想在windows平台的应用开发中使用这个引擎吗?肯定?好,往下看!本文给出Windows平台SpiderMonkey的32位和64位静态库编译方法 WINDOWS-SpiderMonkey32位Release静态库,开心吧?网上2017年以前的例子,你不一定能编译的过

    2022年10月17日
    4
  • 使用 qrcodejs2 生成二维码详细API和参数

    使用 qrcodejs2 生成二维码详细API和参数使用 qrcodejs2 页面引入页面标签可以使 id 或者 ref 建议使 ref 因为使 vue 框架控制虚拟 Dom 才是正确的选择简单 便参数说明 OptionsEvent

    2026年3月17日
    2
  • XFF漏洞利用[通俗易懂]

    XFF漏洞利用[通俗易懂]作者:小刚一位苦于信息安全的萌新小白帽,记得关注给个赞,谢谢本实验仅用于信息防御教学,切勿用于其它用途XFF漏洞X-Forwarded-For(XFF)利用方式1.绕过服务器过滤2.XFF导致sql注入补充X-Forwarded-For(XFF)XFF是header请求头中的一个参数是用来识别通过HTTP代理或负载均衡方式连接到Web服务器的客户端最原始的IP地址的HTTP请求头字段。代表了HTTP的请求端真实的IP。X-Forwarded-For:client1,proxy1,p.

    2022年6月16日
    63

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号