赞
踩
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
1
\
2
/
3
输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
代码(栈实现):
/** * 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*> S; vector<int> v; TreeNode* rt = root; while(rt || S.size()){ while(rt){ //先遍历左子树 S.push(rt);//从根节点开始,把左子树入栈 rt=rt->left; } rt=S.top();S.pop();//利用栈的特性,先进后出 v.push_back(rt->val);//记录节点的值 rt=rt->right; } return v; } };
代码(递归实现):
/** * 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: void traversal(TreeNode* root,vector<int>& res) { if(root == NULL) return; traversal(root->left,res); res.push_back(root->val); traversal(root->right,res); } vector<int> inorderTraversal(TreeNode* root) { vector<int> res; traversal(root,res); return res; } };
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。