二叉树的中序遍历(栈实现)

题目: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 {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        /*
        *中序遍历:左 中 右
        */
        vector<int> ans;
        stack<TreeNode*> st;
        st.push(root);
        TreeNode* cur,*tmp;
        while(!st.empty()) {
            cur = st.top();
            st.pop();
            if(cur == NULL) continue;
            if(cur->right != NULL) st.push(cur->right);//右子树最后
            if(cur->left == NULL)
                ans.push_back(cur->val);
            else {
                tmp = cur->left;
                cur->left = cur->right = NULL;
                st.push(cur);
                st.push(tmp);
            }
        }
        return ans;
    }
};

你可能感兴趣的:(leetcode)