前序遍历:根左右
//用栈来实现非递归解法/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> preorderTraversal(TreeNode* root) { vector<int> res; if(root == NULL) return res; stack<TreeNode*> stack; stack.push(root); while(!stack.empty()){ TreeNode* c = stack.top(); stack.pop(); res.push_back(c->val); if(c->right) stack.push(c->right); if(c->left) stack.push(c->left); } return res; } };
//递归解法,注意res是全局的,要放在遍历函数外面/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> res; vector<int> preorderTraversal(TreeNode* root) { if(root){ res.push_back(root->val); preorderTraversal(root->left); preorderTraversal(root->right); } return res; } };
中序遍历:左根右
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<int> inorderTraversal(TreeNode* root) { stack<TreeNode*> st; vector<int> res; if(root == NULL) return res; //若根节点为空则返回空 TreeNode* p = root; while(p || !st.empty()){ while(p){ //先将根节点入栈,再将它所有的左节点入栈 st.push(p); p = p->left; } p = st.top(); st.pop(); res.push_back(p->val); p = p->right; } return res; } };
原文地址:https://www.cnblogs.com/Bella2017/p/10279952.html
时间: 2024-10-14 17:13:16