Showing posts with label Tree Traversal. Show all posts
Showing posts with label Tree Traversal. Show all posts

Tuesday, September 29, 2009

Code to traverse TreeView and generate the possible paths using C#


Here is the sample code for traversing the TreeView control and generating the possible paths


private void btnGeneratePathsFile_Click(object sender, EventArgs e)
        {
            foreach (TreeNode _rootNode in tvPath.Nodes)
            {
                TreeNode leafNode = FindLeafNode(_rootNode);
                //Result.Add(leafNode.FullPath.Replace("\\", " "));
            }
            System.IO.StreamWriter myFile = new System.IO.StreamWriter("c:\\output.txt");
            foreach (string strVal in Result)
            {
                myFile.WriteLine(strVal);
            }
            myFile.Close();

        }



TreeNode FindLeafNode(TreeNode RootNode)
        {
            TreeNode leafNode = default(TreeNode);
            leafNode = RootNode;
            foreach (TreeNode subNode in RootNode.Nodes)
            {
                if (subNode.Nodes.Count > 0)
                    leafNode = FindLeafNode(subNode);
                else
                    Result.Add(subNode.FullPath.Replace("\\", " "));
            }
            return leafNode;
        }