1. 程式人生 > >力扣算法題—094中序遍歷二叉樹【】

力扣算法題—094中序遍歷二叉樹【】

中序 非遞歸 輸入 root urn clas 進階 else oid

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

示例:

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

輸出: [1,3,2]

進階: 遞歸算法很簡單,你可以通過叠代算法完成嗎?

 1 //遞歸遍歷
 2 class Solution {
 3 public:
 4     vector<int> inorderTraversal(TreeNode* root) {
 5         vector<int>res;
 6         helper(res, root);
 7         return
res; 8 } 9 void helper(vector<int>&res, TreeNode* root) { 10 if (root==NULL) 11 return; 12 if (root->left) 13 helper(res, root->left); 14 res.push_back(root->val); 15 if (root->right) 16 helper(res, root->right);
17 } 18 }; 19 20 21 //非遞歸遍歷 22 class Solution { 23 public: 24 vector<int> inorderTraversal(TreeNode* root) { 25 vector<int>res; 26 stack<TreeNode*>s; 27 TreeNode* p = root; 28 while (p || !s.empty()) { 29 while (p) { 30
s.push(p); 31 p = p->left; 32 }//找到最左節點 33 p = s.top(); 34 s.pop(); 35 res.push_back(p->val); 36 p = p->right; 37 } 38 return res; 39 } 40 }; 41 42 43 //另一種解法 44 // Non-recursion and no stack 45 class Solution { 46 public: 47 vector<int> inorderTraversal(TreeNode *root) { 48 vector<int> res; 49 if (!root) return res; 50 TreeNode *cur, *pre; 51 cur = root; 52 while (cur) { 53 if (!cur->left) { 54 res.push_back(cur->val); 55 cur = cur->right; 56 } 57 else { 58 pre = cur->left; 59 while (pre->right && pre->right != cur) pre = pre->right; 60 if (!pre->right) { 61 pre->right = cur; 62 cur = cur->left; 63 } 64 else { 65 pre->right = NULL; 66 res.push_back(cur->val); 67 cur = cur->right; 68 } 69 } 70 } 71 return res; 72 } 73 };

力扣算法題—094中序遍歷二叉樹【】