LeetCode 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> re;   
    vector<int> inorderTraversal(TreeNode* root) {
 
        if(root)
        {   
              inorderTraversal(root->left) ;
              //cout<< root->val<<endl;
            re.push_back(root->val);
              inorderTraversal(root->right);
                  
        }
        return re ;
    }

};

入栈实现二叉树中序遍历

/**
 * 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> re;
    stack<TreeNode*> st;
    vector<int> inorderTraversal(TreeNode* root) {
 //分析    1. 第一次遇到节点 入栈   然后遍历左子树
        //2. 当左子树遍历完了 ,然后从栈顶弹出节点 并访问它
        //3. 然后再按其右指针去中序遍历该节点的右子树
        while(root || !st.empty())
        {   
            while(root)
            {
                st.push(root) ;
                root = root->left ;  
     
            }

           if(!st.empty())
           {
               re.push_back(st.top()->val);
                root = st.top()->right ;
               st.pop();//出栈
              // root = root->right ;
               //e.push_back(root->val);
           }
                    
        }
        return re ;
    }

};

猜你喜欢

转载自blog.csdn.net/wx734518351/article/details/80260615