F. GCD and LCM ( ICL 2016 (GP of Tatarstan))
阿新 • • 發佈:2021-11-06
45. 二叉樹的後序遍歷
後續遍歷順序:
- 後序遍歷其左子樹;
- 後序遍歷其右子樹;
- 訪問根結點。
解法1:
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 class Solution 11 { 12 public: 13 vector<int> postorderTraversal(TreeNode* root) 14 { 15 vector<int> nums; 16 17 if (!root) 18 return nums; 19 20 stack<TreeNode*> s; 21 TreeNode *p; 22 s.push(root); 23 p = root->left; 24 25 while (!s.empty())26 { 27 while (p != nullptr) 28 { 29 s.push(p); 30 p = p->left; 31 } 32 33 bool flag = true; 34 p = nullptr; 35 36 while (!s.empty() && flag) 37 { 38 root = s.top();39 if (root->right == p) 40 { 41 s.pop(); 42 nums.push_back(root->val); 43 p = root; 44 } 45 else 46 { 47 flag = false; 48 p = root->right; 49 } 50 } 51 } 52 return nums; 53 } 54 };