给定一个二叉树,返回它的中序 遍历。
示例:
输入: [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 { vector<int> mNum; public: vector<int> inorderTraversal(TreeNode* root) { init(); mDfs(root); return mNum; } void mDfs(TreeNode* root) { if (root!= NULL) { mDfs(root->left); //递归左子树 mNum.push_back(root->val); mDfs(root->right); //递归右子树 } } void init() { mNum.clear(); } };
迭代解法:
/** * 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 { vector<int> num; stack<TreeNode* > mNum; public: vector<int> inorderTraversal(TreeNode* root) { init(); bfs(root); return num; } void bfs(TreeNode* root) { while(root!= NULL|| ! mNum.empty()) { while (root!= NULL) { mNum.push(root); root = root->left; //遍历到最左的叶节点 } root = mNum.top(); //取出所在的叶/父节点,存进数组; mNum.pop(); num.push_back(root->val); root = root->right; //遍历右子树; } } void init() { num.clear(); if(! mNum.empty()) mNum.pop(); } };