程序员面试100题---4.在二元树中找出和为某一值的所有路径(树)

来源:互联网 发布:路飞 知乎 编辑:程序博客网 时间:2024/05/21 11:44

4.在二元树中找出和为某一值的所有路径(树)

输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如输入整数22和如下二元树

  10  
  / /   
 5  12   
 /   /   
4   7

则打印出两条路径:10, 1210, 5, 7

-----------------------------------------------

分析,此题的解体过程比较简答,遍历这棵树,从根节点出发,分别左子树右子树,如果路径上从根到某一结点权值和为22,则输出此条路径。此题的关键是这条路径必须包含根结点。


structBinaryTreeNode // 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
}BTnode;

void print_path(BTnode *root , int N)

{

   if(root->m_nValue == N) printf("path:%d,",root->m_nValue);


   if(root->m_pLeft)

   {

      print_path(root->m_pLeft,N - root->m_pLfet->m_nValue);

   }

   if(root->m_pRight)

   {

      print_path(root->m_pLeft,N -root->m_pRight);

   }

}

原创粉丝点击