java 二叉树中和为某一值的路径_25. 二叉树中和为某一值的路径

题目:输入一棵二叉树和一个整数,打印出二叉树中结点值为的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

思路:按照前序遍历的顺序遍历二叉树。将每次遍历的结点保存,然后遍历到叶结点的时候进行计算,计算完之后符合就输出,不符合就返回上一级同时删除叶结点,继续遍历。

10

5    12     从10开始遍历,10,5,4,不符合,删除4返回5。10,5,7符合,输出。删除7,返回

4   7         5,删除5,返回10。10,12符合输出。可以看出符合栈结构。

#include

#include

#include

#include

using namespace std;

struct BinaryTreeNode

{

int m_nValue;

BinaryTreeNode* m_pLeft;

BinaryTreeNode* m_pRight;

};

BinaryTreeNode* CreateNode(int value)

{

BinaryTreeNode* TreeNode = new BinaryTreeNode();

TreeNode->m_nValue = value;

TreeNode->m_pLeft = NULL;

TreeNode->m_pRight = NULL;

return TreeNode;

}

void ConnectTreeNodes(BinaryTreeNode* pRoot, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)

{

if (pRoot)

{

pRoot->m_pLeft = pLeft;

pRoot->m_pRight = pRight;

}

}

//销毁树

void DestroyTree(BinaryTreeNode* pRoot)

{

if (pRoot != NULL)

{

delete pRoot;

pRoot = NULL;

DestroyTree(pRoot->m_pLeft);

DestroyTree(pRoot->m_pRight);

}

}

void FindPath(BinaryTreeNode* pRoot, int expectedSum, vector& path, int& currentSum);

void FindPath(BinaryTreeNode* pRoot, int expectedSum)

{

if (pRoot == NULL)

{

return;

}

vector path;

int currentSum = 0;

FindPath(pRoot, expectedSum, path, currentSum);

}

void FindPath

(

BinaryTreeNode* pRoot,

int expectedSum,

vector& path,

int currentSum

)

{

currentSum += pRoot->m_nValue;

path.push_back(pRoot->m_nValue);

//如果是叶结点,并且路径上结点的和等于输入的值,打印这条路径

bool isLeaf = pRoot->m_pLeft == NULL && pRoot->m_pRight == NULL;

if (currentSum == expectedSum && isLeaf)

{

vector::iterator iter = path.begin();

for (; iter != path.end(); iter++)

{

cout << iter << " ";

}

cout << endl;

}

//如果不是叶结点,则遍历它的子结点

if (pRoot->m_pLeft != NULL)

{

FindPath(pRoot->m_pLeft, expectedSum, path, currentSum);

}

if (pRoot->m_pRight != NULL)

{

FindPath(pRoot->m_pRight, expectedSum, path, currentSum);

}

//在返回父结点之前,在路径上删除当前结点

path.pop_back();

}

void test()

{

BinaryTreeNode* node1 = CreateNode(10);

BinaryTreeNode* node2 = CreateNode(5);

BinaryTreeNode* node3 = CreateNode(12);

BinaryTreeNode* node4 = CreateNode(4);

BinaryTreeNode* node5 = CreateNode(7);

ConnectTreeNodes(node1, node2, node3);

ConnectTreeNodes(node2,node4,node5);

FindPath(node1, 22);

DestroyTree(node1);

}

int main()

{

test();

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值