标签:logs turn vector 中序 pop while 的区别 roo 迭代
给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3] 1 2 / 3 输出: [1,3,2]
进阶: 递归算法很简单,你可以通过迭代算法完成吗?
中序遍历:L--N--R (左--根--右)
class Solution { public: vector<int> inorderTraversal(TreeNode* root) { if(root){ inorderTraversal(root->left); //左 res.push_back(root->val); //根 inorderTraversal(root->right);//右 } return res; } private: vector<int> res; };
/** * 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; //s.push(root); TreeNode* cur = root;// //L--N--R while(cur || !s.empty()) if(cur){ s.push(cur); cur = cur->left; //先走到最左子树 } else{ res.push_back(s.top()->val); cur = s.top()->right; s.pop(); } return res; } private: vector<int> res; };
参考资料:
1.https://blog.csdn.net/swliao/article/details/5337896 递归与迭代的区别
2.https://www.cnblogs.com/ariel-dreamland/p/9159638.html
标签:logs turn vector 中序 pop while 的区别 roo 迭代
原文地址:https://www.cnblogs.com/paulprayer/p/10101272.html