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

二元树路径查找
本文介绍了一种在二元树中查找所有节点之和等于指定数值的路径的方法,并提供了使用C#实现的具体代码示例。

4.在二元树中找出和为某一值的所有路径
题目:输入一个整数和一棵二元树。
从树的根结点开始往下访问一直到叶结点所经过的所有结点形成一条路径。
打印出和与输入整数相等的所有路径。
例如 输入整数22和如下二元树
10
/ /
5 12
/ /
4 7
则打印出两条路径:10, 12和10, 5, 7。

C# codes as below:

using System;

using System.Collections.Generic;

namespace ConsoleApp

{

class RunClass

{

static void Main()

{

Node<int> i1 = new Node<int>() { Value = 4 };

Node<int> i2 = new Node<int>() { Value = 7 };

Node<int> i3 = new Node<int>() { Value = 12 };

Node<int> i5 = new Node<int>() { Value = 5, Left = i1, Right = i2 };

Node<int> i7 = new Node<int>() { Value = 10, Left = i5, Right = i3 };

Tree<int> myTree = new Tree<int>() { Root = i7 };

new Helper().PrintPath(myTree, 22);

Console.ReadKey();

}

}

class Helper

{

public void PrintPath(Tree<int> tree, int value, Node<int> node=null)

{

Node<int> root = tree.Root;

if (node == null)

{

node = new Node<int>() { Value = root.Value };

}

if (root.Left != null)

{

Node<int> newNode = new Node<int>() { Value = root.Left.Value, Left = node };

PrintPath(new Tree<int>() { Root = root.Left }, value - root.Value, newNode);

}

if (root.Right != null)

{

Node<int> newNode = new Node<int>() { Value = root.Right.Value, Left = node };

PrintPath(new Tree<int>() { Root = root.Right }, value - root.Value, newNode);

}

if (root.Left == null && root.Right == null)

{

if (root.Value == value)

{

Stack<int> stack = new Stack<int>();

do

{

stack.Push(node.Value);

node = node.Left;

}

while (node != null);

foreach (int nodeValue in stack)

{

Console.Write("{0} ", nodeValue);

}

Console.WriteLine();

}

}

}

}

class Node<T>

{

public Node<T> Left { get; set; }

public Node<T> Right { get; set; }

public T Value { get; set; }

}

class Tree<T>

{

public Node<T> Root { get; set; }

}

}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值