题解 | #二叉树的中序遍历# (非递归)

二叉树的中序遍历

https://www.nowcoder.com/practice/0bf071c135e64ee2a027783b80bf781d

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 
 
 */
#include <stack>
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型vector
     */


    vector<int> inorderTraversal(TreeNode* root) {
      std::vector<int> result;
      std::stack<TreeNode*> st;
      TreeNode* cur = root;
      while (cur || !st.empty()) {
        while (cur != nullptr) {
          st.push(cur);
          cur = cur->left;
        }

        // 取出栈顶节点,然后访问,该节点的左子树要么为空;
        // 要么已被访问过了
        auto top = st.top();
        st.pop();
        result.push_back(top->val);
        
        // 解决右子树子问题
        cur = top->right;
      }

      return result;
    }
};

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务