标签:turn lse string roo 节点 root 访问 class color
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 static int wing=[]() 11 { 12 std::ios::sync_with_stdio(false); 13 cin.tie(NULL); 14 return 0; 15 }(); 16 17 class Solution 18 { 19 public: 20 vector<string> binaryTreePaths(TreeNode* root) 21 { 22 vector<string> res; 23 TreeNode *p=root,*r=NULL; 24 stack<TreeNode*> s,h; 25 while(p||!s.empty()) 26 { 27 if(p) 28 { 29 s.push(p); 30 p=p->left; 31 } 32 else 33 { 34 p=s.top(); 35 if(p->right&&p->right!=r) 36 { 37 p=p->right; 38 s.push(p); 39 p=p->left; 40 } 41 else 42 { 43 if(p->left==NULL&&p->right==NULL) 44 { 45 h=s; 46 string cur; 47 int sz=h.size(); 48 while(sz>1) 49 { 50 TreeNode *ps=h.top(); 51 int value=ps->val; 52 cur="->"+to_string(value)+cur; 53 sz--; 54 h.pop(); 55 } 56 TreeNode *last=h.top(); 57 int lastvalue=last->val; 58 cur=to_string(lastvalue)+cur; 59 res.push_back(cur); 60 } 61 s.pop(); 62 r=p; 63 p=NULL; 64 } 65 } 66 } 67 return res; 68 } 69 };
利用后序遍历,在出栈访问节点时判定节点是否为叶节点,若是叶节点,就生成字符串并添加至结果中。
标签:turn lse string roo 节点 root 访问 class color
原文地址:https://www.cnblogs.com/zhuangbijingdeboke/p/9084589.html