#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
using namespace std;
struct binaryTreeNode
{
int m_nValue;
binaryTreeNode* m_pLeft;
binaryTreeNode* m_pRight;
};
//创建二叉树的程序
void CreatBinaryTree(binaryTreeNode* &root, int data[], int i, int n)
{
if (i <= n)
{
root = new binaryTreeNode;
root->m_nValue = data[i - 1];
CreatBinaryTree(root->m_pLeft, data, 2 * i, n);
CreatBinaryTree(root->m_pRight, data, 2 * i + 1, n);
}
else
root = nullptr;
}
void PrintTreeNode(binaryTreeNode* pNode)
{
if (pNode != nullptr)
{
cout << "value of this node is" << pNode->m_nValue << endl;
if (pNode->m_pLeft != NULL)
cout << "value of its left child is" << pNode->m_pLeft->m_nValue << endl;
else
cout << "left child is null." << endl;
if (pNode->m_pRight != NULL)
printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
else
printf("right child is null.\n");
}
else
{
printf("this node is null.\n");
}
printf("\n");
}
void PrintTree(binaryTreeNode* pRoot)
{
PrintTreeNode(pRoot);//连续的调用这个函数去显示二叉树
if (pRoot != NULL)
{
if (pRoot->m_pLeft != NULL)
PrintTree(pRoot->m_pLeft);
if (pRoot->m_pRight != NULL)
PrintTree(pRoot->m_pRight);
}
}
//////////////////////////////////
////////////////////////////////
//二叉树输出路径
vector<string> TreePaths;
void DFS(binaryTreeNode* node, string answer)
{
answer += "->" + to_string(node->m_nValue);
if (node->m_pLeft == NULL && node->m_pRight == NULL)
TreePaths.push_back(answer);
else
{
if (node->m_pLeft!= NULL)
DFS(node->m_pLeft, answer);
if (node->m_pRight!= NULL)
DFS(node->m_pRight, answer);
}
}
vector<string> binaryTreePaths(binaryTreeNode* root) {
if (root != NULL)
{
DFS(root, "");
for (int i = 0; i < TreePaths.size(); i++)
TreePaths[i].erase(TreePaths[i].begin(), TreePaths[i].begin() + 2);
}
return TreePaths;
}
//测试
int main()
{
vector<string>result;
binaryTreeNode* root;
//root->mRight->mRight = nullptr;
int data[8] = { 1,2,3,4,5,6,7,8};
CreatBinaryTree(root, data, 1, 8);
PrintTree(root);
result=binaryTreePaths(root);
for (auto c : result)
cout << c << endl;
}
Leetcode 二叉树的路径输出
最新推荐文章于 2024-07-30 21:02:05 发布