首页 > 编程知识 正文

求根节点到叶子节点路径,如何求树的叶子节点

时间:2023-05-04 11:37:52 阅读:193979 作者:4065

简记一篇,项目中需要使用流程图自定义执行过程,遍历流程图节点执行代码操作(类似Arcmap Modelbuilder),实际上就是关于树形结构从根节点到叶子节点的路径遍历输出,本篇以二叉树结构为例。
上图的输出结果应该为:1-2-4-7 1-2-5-8 1-3-6-9 1-3-6-10

public class Node { private int _value = 0; private Node _left = null; private Node _right = null; public int Value { get { return this._value; } set { this._value = value; } } public Node Left { get { return this._left; } set { this._left = value; } } public Node Right { get { return this._right; } set { this._right = value; } } public Node(int value) { this._value = value; } } public class TreeNodeHelper { private List<List<int>> _allpaths = new List<List<int>>(); private List<int> _flagpath = new List<int>(); public List<List<int>> FindAllPath(Node root) { if (root == null) return this._allpaths; _flagpath.Add(root.Value); if (root.Left == null && root.Right == null) { _allpaths.Add(new List<int>(_flagpath)); } FindAllPath(root.Left); FindAllPath(root.Right); //主要在这个地方的理解:二叉树中没有右节点,则回退,直到找到一个有右节点的分支点为止 //(这样说可能也不是很清楚,如果你想弄清楚,建议把这个方法的流程重新调试一下吧,那样你会看的更加清楚了!) _flagpath.RemoveAt(_flagpath.Count - 1); return _allpaths; } }

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。