1. 程式人生 > >leetcode 145. 二叉樹的後序遍歷

leetcode 145. 二叉樹的後序遍歷

叠代算法 left color lee clu tor pre 後序 struct

給定一個二叉樹,返回它的 後序 遍歷。

示例:

輸入: [1,null,2,3]  
   1
         2
    /
   3 

輸出: [3,2,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 public: 12 void dfs(TreeNode* root, vector<int>& ans){ 13 if(root == NULL) return; 14 if(root->left) dfs(root->left, ans); 15 if(root->right) dfs(root->right, ans); 16 ans.push_back(root->val); 17 }
18 vector<int> postorderTraversal(TreeNode* root) { 19 vector<int> ans; 20 dfs(root, ans); 21 return ans; 22 } 23 };

叠代的實現:用棧的方式來實現

 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 #include<stack> 11 class Solution { 12 public: 13 vector<int> postorderTraversal(TreeNode* root) { 14 stack<TreeNode*> s; 15 s.push(root); 16 vector<int> ans; 17 if(root == NULL) return ans; 18 while(!s.empty()){ 19 TreeNode* temp = s.top(); 20 if(temp->left){ 21 s.push(temp->left); 22 temp->left = NULL; 23 } else if(temp->right){ 24 s.push(temp->right); 25 temp->right = NULL; 26 } else{ 27 ans.push_back(temp->val); 28 s.pop(); 29 } 30 } 31 return ans; 32 } 33 };

leetcode 145. 二叉樹的後序遍歷