100.(94)二叉树的中序遍历

    技术2022-07-11  94

    题目描述:

    给定一个二叉树,返回它的中序 遍历。

    示例:

    输入: [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) { vector<int> res; TreeNode *root_1=root,*root_2; stack<TreeNode*> s; while(!s.empty()||root_1) { if(root_1) { s.push(root_1); root_1=root_1->left; } else { root_2=s.top(); res.push_back(root_2->val); root_1=root_2->right; s.pop(); } } return res; } };

    执行效率:

    执行用时:0 ms, 在所有 C++ 提交中击败了100.00%的用户

    内存消耗:7.2 MB, 在所有 C++ 提交中击败了100.00%的用户

    Processed: 0.011, SQL: 9