输出二叉树中所有从根结点到叶子结点的路径

// 输出二叉树中所有从根结点到叶子结点的路径.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include <iostream>
#include <vector>
using namespace std;

struct BTNode
{
	char m_value;
	BTNode *m_left;
	BTNode *m_right;
};

//先序创建二叉树
void CreatBTree(BTNode *&root)
{	
	char nValue = 0;
	cin >> nValue;
	if ('#' == nValue)
	{
		return;
	}
	else
	{
		root = new BTNode();
		root->m_value = nValue;
		CreatBTree(root->m_left);
		CreatBTree(root->m_right);
	}	
}

//输出二叉树中所有从根结点到叶子结点的路径(递归)
void FindAllPath(BTNode *pRoot, vector<char> path)
{
	if (pRoot != NULL)
	{
		path.push_back(pRoot->m_value);
		if (pRoot->m_left == NULL && pRoot->m_right == NULL)
		{
			for (vector<char>::iterator iter=path.begin(); iter!=path.end(); iter++)
			{
				cout << *iter << " ";
			}
			cout << endl;
			return;
		}
		else
		{
			FindAllPath(pRoot->m_left, path);
			FindAllPath(pRoot->m_right, path);
		}
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	BTNode *pRoot = NULL;
	vector<char> path;
	CreatBTree(pRoot);
	cout << "二叉树中从根到叶子结点的所有路径如下:" << endl;
    FindAllPath(pRoot, path);
	system("pause");
	return 0;
}

运行结果:


  • 3
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 可以使用深度优先搜索(DFS)来输出叉树每个叶子结点到根点的路径。具体步骤如下: 1. 定义一个栈,用于存储遍历过的点和路径。 2. 从根点开始,将根点和空路径入栈。 3. 当栈不为空时,弹出栈顶元素,如果该点是叶子结点,则输出路径。 4. 如果该点不是叶子结点,则将其左右子点和路径入栈,路径为当前路径加上该点的值。 5. 重复步骤3-4,直到栈为空。 代码实现如下: ```python class TreeNode: def __init__(self, val=, left=None, right=None): self.val = val self.left = left self.right = right def print_leaf_to_root_path(root): if not root: return stack = [(root, "")] while stack: node, path = stack.pop() if not node.left and not node.right: print(path + str(node.val)) if node.left: stack.append((node.left, path + str(node.val) + "->")) if node.right: stack.append((node.right, path + str(node.val) + "->")) ``` 例如,对于以下二叉树: ``` 1 / \ 2 3 / \ 4 5 ``` 输出果为: ``` 4->2->1 5->2->1 3->1 ``` ### 回答2: 二叉树每个叶子节点到根节点的路径,指的是从二叉树的叶子节点开始,通过所有父节点一路走到到根节点的路径。这个问题可以用递归和非递归两种方法来解决: 1. 递归方法 从根节点开始,递归地遍历整个二叉树,当遇到叶子节点时,输出从该叶子节点到根节点的路径。具体实现步骤如下: - 定义一个字符串变量path,用来存储路径。 - 从根节点开始,递归地遍历二叉树,如果当前节点是叶子节点,则输出路径,并回溯到父节点。 - 递归函数的参数,需要传入当前节点、path以及path的长度,以方便在回溯时删除已经过的节点。 具体代码实现如下: ```python # 定义二叉树构 class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right # 递归方法 def printPath(root, path="", length=0): if not root: return path_list = [] path = path + str(root.val) length = length + 1 if not root.left and not root.right: for i in range(length): path_list.append(path[i]) print("".join(path_list)) printPath(root.left, path, length) printPath(root.right, path, length) path = path[:-1] length = length - 1 # 测试代码 if __name__ == '__main__': n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n7 = TreeNode(7) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 printPath(n1) ``` 2. 非递归方法 非递归方法采用迭代的方式,使用栈来保存每个非叶子节点以及已经过的路径。具体实现步骤如下: - 创建一个栈,将根节点和空字符串入栈。其,空字符串代表根节点不需要经过其他节点。 - 当栈不为空时,取出栈顶元素,如果它是叶子节点,则输出路径;否则,将它的左右子节点以及路径分别入栈。 具体代码实现如下: ```python # 非递归方法 def printPath(root): if not root: return stack = [(root, "")] while stack: node, path = stack.pop() if not node.left and not node.right: print(path + str(node.val)) if node.left: stack.append((node.left, path + str(node.val))) if node.right: stack.append((node.right, path + str(node.val))) # 测试代码 if __name__ == '__main__': n1 = TreeNode(1) n2 = TreeNode(2) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5) n6 = TreeNode(6) n7 = TreeNode(7) n1.left, n1.right = n2, n3 n2.left, n2.right = n4, n5 n3.left, n3.right = n6, n7 printPath(n1) ``` ### 回答3: 二叉树是一种非常常见的树型数据构,也是面试最经常被问到的数据构之一,其一个关键的操作就是输出叉树每个叶子节点到根节点的路径。本文将详细介绍如何实现这个操作。 首先我们需要明确什么是叶子节点和根节点。二叉树的叶子节点指的是没有子节点的节点,而根节点则是整个树形构的顶端节点,它没有父节点。 要输出叉树每个叶子节点到根节点的路径可以利用DFS深度优先搜索的思想,从叶子节点一直向上搜索直到根节点。我们可以使用一个栈来保存搜索过程路径,每当搜索到一个叶子节点,就输出的内容,得到一条从叶子节点到根节点的路径。在输出路径后需要清空栈,准备下一个搜索。 代码实现可以参考下面的伪代码: ``` void printPathToRoot(TreeNode* root) { if (root == NULL) return; stack<TreeNode*> path; printPath(root, path); } void printPath(TreeNode* node, stack<TreeNode*>& path) { if (node == NULL) return; path.push(node); if (node->left == NULL && node->right == NULL) { // 已经到达叶子节点,输出路径 printStack(path); } else { printPath(node->left, path); printPath(node->right, path); } path.pop(); // 在返回父节点之前需要弹出当前节点 } void printStack(stack<TreeNode*>& path) { // 将栈的内容倒序输出即可得到路径 stack<TreeNode*> temp; while (!path.empty()) { temp.push(path.top()); path.pop(); } while (!temp.empty()) { cout << temp.top()->val << " "; path.push(temp.top()); temp.pop(); } cout << endl; } ``` 上述代码,printPathToRoot函数是入口函数,它会调用printPath函数来搜索每个节点。printPath函数会传入当前节点和一个栈,如果当前节点是叶子节点,就输出的内容即可得到从叶子节点到根节点的路径;否则继续搜索左右子树。在返回父节点之前需要弹出当前节点。 printStack函数用于将栈的内容倒序输出,正序输出是从根节点到叶子节点,而我们需要从叶子节点到根节点输出路径。 总之,输出叉树每个叶子节点到根节点的路径需要通过DFS搜索实现,利用栈保存搜索过程路径,每当搜索到一个叶子节点,就输出一条从叶子节点到根节点的路径。这个操作对于理解二叉树数据构的特点和熟悉DFS算法都非常有帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值