二叉树遍历

 前序遍历

 思路:前序遍历算法先访问树的根节点,然后遍历左子树,最后遍历右子树。

解法1

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<int> preorderTraversal(TreeNode* root) 
15     {
16         if(!root) return {};
17         stack<TreeNode *> st;
18         vector<int> res;
19         TreeNode *p = root;
20         st.push(p);
21         while(!st.empty())
22         {
23             p = st.top();
24             st.pop();
25             res.push_back(p->val);
26             
27             if(p->right) st.push(p->right);
28             if(p->left) st.push(p->left);
29         }
30         return res;
31     }
32 };

 

中序遍历

思路:中序遍历的算法先遍历左子树,然后访问根节点,最后遍历右子树。

 

 

解法1:非递归遍历

 

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<int> inorderTraversal(TreeNode* root) 
15     {
16         if(!root) return {};
17         
18         vector<int> res;
19         stack<TreeNode *> st;
20         TreeNode *p = root;
21         
22         while(!st.empty() || p)
23         {
24             while(p)
25             {
26                 st.push(p);
27                 p = p->left;
28             }
29             p = st.top();
30             st.pop();
31             res.push_back(p->val);
32             
33             p = p->right;
34         }
35         return res;
36     }
37 };

 

posted @ 2021-09-13 21:05  苏格拉底的落泪  阅读(41)  评论(0编辑  收藏  举报