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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wucdsg/article/details/88832597

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

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/wucdsg/article/details/88832597