#include "stdafx.h" #include <vector> #include <iostream> using namespace std; #define A 16 //二叉树前序遍历序列 int buffer[16]={1,2,4,-1,-1,5,-1,-1,3,6,-1,-1,7,-1,-1,-100}; //二叉树结构体 typedef struct binary_tree_node { int data; struct binary_tree_node* ltree; struct binary_tree_node* rtree; }Btnode; //创建新节点 Btnode* create_node(void) { Btnode* node; node=(Btnode*)malloc(sizeof(Btnode)); return node; } //据前序序列创建二叉树 /* 明白问题: (1)何时进行二叉树分支的切换 ①左分支遍历到叶子节点时 ②右分支有新的节点增加时 (2)何时节点入栈 新增加的非空节点 (3)何时节点出栈 某分支遍历到叶子节点时 */ Btnode* create_tree(int* buf) { Btnode* root; Btnode* pnode,*temp; Btnode* s[A]; bool ltree=true; int index=0; int m=0; root=create_node(); root->data=buf[index++]; s[m++]=root; pnode=root; while(buf[index]!=-100) { if(ltree==true) { if(buf[index]==-1) { pnode->ltree=NULL; index++; ltree=false; pnode=s[--m]; } else { temp=create_node(); temp->data=buf[index++]; pnode->ltree=temp; s[m++]=temp; pnode=temp; } } else { if(buf[index]==-1) { pnode->rtree=NULL; index++; pnode=s[--m]; } else { temp=create_node(); temp->data=buf[index++]; pnode->rtree=temp; s[m++]=temp; pnode=temp; ltree=true; } } } return root; } //递归方法前序遍历 void preorder_traversal(Btnode* pnode) { if(pnode!=NULL) { printf("%d ",pnode->data); } else { return; } preorder_traversal(pnode->ltree); preorder_traversal(pnode->rtree); return; } vector<Btnode*> s; int sum=0; int SPEC=100; void printPath(void) { vector<Btnode*>::iterator it=s.begin(); cout<<" Path: "; while(it!=s.end()) { cout<<(*it)->data<<" "; ++it; } cout<<endl; } void postSum(Btnode* node) { if(node->ltree==NULL && node->rtree==NULL) { sum+=node->data; s.push_back(node); //if(sum==SPEC) { cout<<sum<<" "; printPath(); } if(!s.empty()) { sum-=s.back()->data; s.pop_back(); } return; } else { sum+=node->data; s.push_back(node); postSum(node->ltree); postSum(node->rtree); } if(!s.empty()) { sum-=s.back()->data; s.pop_back(); } return; } int main(void) { Btnode* root; root=create_tree(buffer); postSum(root); system("pause"); return 0; }