树结构从根节点到叶子节点路径遍历输出

简记一篇,项目中需要使用流程图自定义执行过程,遍历流程图节点执行代码操作(类似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;
        }
    }

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值