急!在线等!!求出2叉树中给定一个节点到根节点的路径 用C#实现 拜托啊!!

来源:百度知道 编辑:UC知道 时间:2024/06/30 13:28:14

看你二叉树是怎么定义的,如果二叉树里面保存有父节点属性的话那就利用迭代就可以很轻松找到根节点了,如果没有的话那就每次往上一级就物理遍历一下二叉树,看那个树的下级子节点是这个,不过一般都会有父节点属性的

假设二叉树节点的类是TreeNode,节点的Parent属性是父节点

public TreeNode getRoot(TreeNode node)
{
if (node.Parent==null) return node; else return getRoot(node);
}

调用时只需要调用getRoot函数,返回值就是它的根节点了

public partial class FrmArea : Form
{
private DataTable _areadatas;
public FrmArea()
{
InitializeComponent();
}
public event SelectArea MySelect = null;
private void button1_Click(object sender, EventArgs e)
{
TreeNode root = new TreeNode();
root.Text = textBox1.Text;
root.ImageIndex = 0;
this.treArea.Nodes.Add(root);
}
private void button2_Click(object sender, EventArgs e)
{
TreeNode node = new TreeNode();
node.Text = textBox1.Text;
no