leecode第九十四题(二叉树的中序遍历)

/**
 * 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> result;
        if(root==NULL)//判断边界
            return result;
        
        stack<TreeNode*> sta;//用栈结构,首先把根节点及所有左子节点打进去
        TreeNode* head=root;
        while(head!=NULL)
        {
            sta.push(head);
            head=head->left;
        }
        
        while(!(sta.empty()&&head->right==NULL))//除非栈为空且右孩子为NULL
        {
            head=sta.top();//否则就弹出栈的top
            sta.pop();
            
            result.push_back(head->val);//记录其值
            
            if(head->right!=NULL)//如果top有右孩子
            {
                head=head->right;//把右孩子及其所有左孩子节点打进栈
                while(head!=NULL)
                {
                    sta.push(head);
                    head=head->left;
                }
            }
        }
        return result;
    }
};

分析:

使用栈结构实现迭代。

https://www.cnblogs.com/qjmnong/p/9135386.html

posted @ 2019-07-19 16:02  深夜十二点三十三  阅读(110)  评论(0编辑  收藏  举报