Finding all possible paths in graph

大兔子大兔子 提交于 2019-12-05 18:08:57

Just fold the result and count the new possibilities: Result = 9 (you forgott the path [1] )

n0  n1  n2  n3
1,   2,  4,       +3
    (2), 5,       +1
    (2), 6,       +1
    (2),          +0
(1), 3,  7,  8,   +3
        (7), 9    +1

You can use this algorithm on a binary tree to print out all of its root-to-leaf paths. The function treePaths traverses the nodes depth-first (DFS), pre-order, recursively.

treePaths(root, path[1000], 0) // initial call, 1000 is a path length limit

// treePaths traverses nodes of tree DFS, pre-order, recursively
treePaths(node, path[], pathLen)
    1) If node is not NULL then 
        a) push data to path array: 
            path[pathLen] = node->data.
        b) increment pathLen 
            pathLen++
    2) If node is a leaf node, then print the path array, from 0 to pathLen-1
    3) Else
        a) Call treePaths for left subtree
            treePaths(node->left, path, pathLen)
        b) Call treePaths for right subtree.
            treePaths(node->right, path, pathLen)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!