给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
2
/
3
输出: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
/**
给定一个二叉树,返回它的中序?遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/binary-tree-inorder-traversal
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
书中非递归的方法是用栈实现的,而这里没有栈操作,但是给了动态数组,熟悉动态数组的用法以后可以用其代替栈操作
* 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) {
vector<int> num;
vector<TreeNode *>point;
//if(root==NULL)
// return num;//此题不能使用递归方法,,返回的不是节点元素 ,而是一个动态数组
TreeNode *p=root;
while(p!=NULL||point.size()!=0)//指针数组中有指针的话也得继续运行
{
if(p!=NULL)
{
point.push_back(p);//存入指针数组(入栈)
p=p->left;
}
else
{
p=point[point.size()-1];//从指针数组中取出最后一个指针(出栈)
point.pop_back();//删除
num.push_back(p->val);//添加值
p=p->right;//指向右孩子
}
}
return num;//返回动态数组
}
};
书上使用栈实现,这里只能用动态数组代替,附上动态数组的知识
https://www.runoob.com/w3cnote/cpp-vector-container-analysis.html