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

被折叠的 条评论
为什么被折叠?



