找出二叉樹中和爲某值的所有路徑

問題是這樣的,在一棵以root爲根的樹中,找出以root爲起點的所有路徑,要求路徑中節點的值相加等於給定的數值。這個問題很簡單,甚至於想都不用想就知道遍歷樹一遍就可以解決。

找出符合要求的路徑,其實就是下面這個遞歸表達式:
1.求出以root爲節點和等於v的路徑;
2.如果root->value等於v,那麼找到一條路徑,返回;
3.如果root->value大於v,那麼就分別找出以root左右孩子爲根的和等於v – root->value的路徑;
4.如果root->value小於v,那麼就不存在符合條件的路徑。
代碼表示如下。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

struct tree {
	int value;
	struct tree *lchild;
	struct tree *rchild;
};

struct tree *insert(struct tree *root, int value)
{
	if (root) {
		if (value < root->value) {
			root->lchild = insert(root->lchild, value);
		} else {
			root->rchild = insert(root->rchild, value);
		}
	} else {
		root = new struct tree;
		root->value = value;
		root->lchild = 0;
		root->rchild = 0;
	}
	return root;
}

void print_tree_prefix(struct tree *root, string pfx)
{
	if (root) {
		if (root->lchild) {
			cout << pfx << "|" << endl;
			if (root->rchild) {
				cout << pfx << "|-<L> " << root->lchild->value << endl;
				print_tree_prefix(root->lchild, pfx + "|     ");
		    	} else {
				cout << pfx << "`-<L> " << root->lchild->value << endl;
			}
		}
		if (root->rchild) {
		    cout << pfx << "|" << endl;
		    cout << pfx << "`-<R> " << root->rchild->value << endl;
		    print_tree_prefix(root->rchild, pfx + "      ");
		}
	}
}

void print_tree(struct tree *root)
{
	if (root) {
	    cout << root->value << endl;
	    print_tree_prefix(root, "");
	}
}

string itos(int i)
{
	string str;
	stringstream s;
	s << i;
	s >> str;
	return str;
}

void sum_prefix(struct tree *root, int v, string pfx)
{
	if (root) {
		if (v == root->value) {
			cout << pfx << root->value << endl;
		} else if (v > root->value) {
			v -= root->value;
			pfx += itos(root->value) + "+";
			sum_prefix(root->lchild, v, pfx);
			sum_prefix(root->rchild, v, pfx);
		}
	}
}

void sum(struct tree *root, int v)
{
	if (root) {
		sum_prefix(root, v, itos(v) + "=");
	}
}

int main()
{
	struct tree *root = 0;
	root = insert(root,  10);
	root = insert(root,   5);
	root = insert(root,   4);
	root = insert(root,   7);
	root = insert(root,  12);
	root = insert(root,  23);
	root = insert(root,   1);
	root = insert(root,   6);
	root = insert(root,   2);
	print_tree(root);
	sum(root, 22);
	return 0;
}


發佈了29 篇原創文章 · 獲贊 2 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章