标签:中序遍历 def cto roo turn 最简 traversal 遍历 tree
/*
给定一个二叉树的根节点 root ,返回它的 中序 遍历。
输入:root = [1,null,2,3]
输出:[1,3,2]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
*/
递归,最简单:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> q;
dfs(root, q);
return q;
}
void dfs(TreeNode *node, vector<int> &ans){
if(node == nullptr) return;
dfs(node->left, ans);
ans.push_back(node->val);
dfs(node->right, ans);
}
};
迭代(用栈实现)
和递归一样,得左边的节点先入栈,然后处理中间,再处理右边
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
if(root == nullptr) return {};
stack<TreeNode *> st;
vector<int> ans;
while(root != nullptr || !st.empty()){
// 右边的节点入栈(左)
while(root != nullptr){
st.push(root);
root = root->left;
}
// 弹出当前节点(中)
root = st.top();
st.pop();
ans.push_back(root->val);
// 到右边去(右)
root = root->right;
}
return ans;
}
};
染色法(0代表没用过,1代表用过,入栈顺序和递归顺序反着来)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
stack<pair<TreeNode*, int>> st;
vector<int> ans;
st.push({root,0});
while(!st.empty()){
auto node = st.top().first;
auto color = st.top().second;
st.pop();
if(node == nullptr){
continue;
}
if(color == 0){
st.push(make_pair(node->right,0));
st.push(make_pair(node,1));
st.push(make_pair(node->left,0));
}else{
ans.push_back(node->val);
}
}
return ans;
}
};
标签:中序遍历 def cto roo turn 最简 traversal 遍历 tree
原文地址:https://www.cnblogs.com/cxl-/p/14589305.html