畫圖可以幫助我們理解,舉個簡單的例子可以看出儲存路徑的資料結構實際就是棧,而遞迴呼叫的本質就是壓棧和出棧的過程。
#include #include #include #include using namespace std;
struct binarytreenode
;void findpath(binarytreenode *proot, int expectedsum, vector&path, int currentsum);
binarytreenode* createbinarytreenode(int value)
void connecttreenodes(binarytreenode* pparent, binarytreenode* pleft, binarytreenode* pright)
}void printtreenode(binarytreenode* pnode)
else
printf("\n");
}void printtree(binarytreenode* proot)
}void destroytree(binarytreenode* proot)
}void findpath(binarytreenode *proot, int expectedsum)
void findpath(binarytreenode *proot, int expectedsum, vector&path, int currentsum)
printf("\n");
} if (proot->m_pleft != null)
if (proot->m_pright != null)
//在返回到父結點之前,在路徑上刪除當前的結點
path.pop_back();
}// ********************測試**********************
void test(char* testname, binarytreenode* proot, int expectedsum)
// 10
// / \
// 5 12
// /\
// 4 7
// 有兩條路徑上的結點和為22
void test1()
// 10
// / \
// 5 12
// /\
// 4 7
// 沒有路徑上的結點和為15
void test2()
// 5
// /
// 4
// /
// 3
// /
// 2
// /
// 1
// 有一條路徑上面的結點和為15
void test3()
// 1
// \
// 2
// \
// 3
// \
// 4
// \
// 5
// 沒有路徑上面的結點和為16
void test4()
// 樹中只有1個結點
void test5()
// 樹中沒有結點
void test6()
void main()
二叉樹中和為某一值得路徑 劍指Offer
輸入一顆二叉樹的根節點和乙個整數,列印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。注意 在返回值的list中,陣列長度大的陣列靠前 首先需要遞迴遍歷整棵樹,遍歷完每一條路徑,遍歷的順序是先根節點,然後是左節點,接著是右節點 如果節點的...
二叉樹中和為指定值得路徑
輸入一棵二叉樹和乙個整數,列印出二叉樹中節點值的和為輸入整數的所有路徑。從樹的根節點開始往下一直到葉節點所經過的節點形成一條路徑。示例 給定如下二叉樹,以及目標和 sum 22,5 4 8 11 13 4 7 2 5 1 返回 5,4,11,2 5,8,4,5 definition for a bi...
二叉樹中和為某一值的路徑
include include using namespace std struct node void find path node r,int exceptedsum,vector path,int cursum node buildbtree int a,int i void preorder...