做这一道题主要是为了回顾一下二叉树的中序遍历,其主要思路如下:
/**
* 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) {
TreeNode* p = root;
TreeNode* temp;
stack<TreeNode*> stack;
vector<int> resultVec;
while(p || !stack.empty()){
while(p){
stack.push(p);
p = p->left;
}
if(!stack.empty()){
p = stack.top();
stack.pop();
resultVec.push_back(p->val);
p = p->right;
}
}
return resultVec;
}
};
Leetcode刷题记录--94. Binary Tree Inorder Traversal
原文:https://www.cnblogs.com/yuyuan-bb/p/12606570.html