题目
二叉树的中序遍历
给定一个二叉树的根节点 root ,返回 它的 中序 遍历 。
示例 1:
输入:root = [1,null,2,3]
输出:[1,3,2]
示例 2:
输入:root = []
输出:[]
示例 3:
输入:root = [1]
输出:[1]
提示:
树中节点数目在范围 [0, 100] 内
-100 <= Node.val <= 100
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
相关标签
C++
答案
/**
-
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:
vectorinorderTraversal(TreeNode root) {
vectorres;
if(root == nullptr){
return res;
}stack<TreeNode> s;
auto current = root;
while(current || !s.empty()){
while (current)
{
s.push(current);
current=current->left;
}
current = s.top();
s.pop();
res.push_back(current->val);
current = current->right;}
return res;
}
};
关键
就是要一直push进去左下角,然后中序左中右就要从最左下角开始,然后左处理完处理中数据再处理右子树的数据
标签:right,TreeNode,nullptr,current,算法,11.8,root,left From: https://www.cnblogs.com/minipython-wldx/p/17818178.html