Little-Prince

导航

94. 二叉树的中序遍历

94. 二叉树的中序遍历

 

给定一个二叉树,返回它的中序 遍历。
示例:
输入: [1,null,2,3]
   1
    \
     2
    /
   3
输出: [1,3,2]
 
 
思路:递归方法, 按照 left->root->right 遍历 时间复杂度 o(n),空间复杂度最坏 o(n),平均 o(log(n))
 
代码:
/**
 * 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 {
      vector<int> result;
public:
    vector<int> inorderTraversal(TreeNode* root) {
      
        if(root)
        {
          inorderTraversal(root->left);
          result.push_back(root->val);
          inorderTraversal(root->right);
        }
        return result;   
    }
};

 

迭代法

思路:使用栈存储访问过的节点 按照 left->root->right 的顺序。时间复杂度 o(n),空间复杂度 o(n)。

代码:

/**
 * 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) {
        stack<TreeNode*> st;
        vector<int> result;
        TreeNode *current  = root;
        while(!st.empty()||current)
        {
              while(current)
                {
                    st.push(current);
                    current = current->left;
                }
                current = st.top();
                result.push_back(current->val);
                st.pop();
                current = current->right;
        }
        return result;
    }
};

 

posted on 2020-08-01 23:20  Little-Prince  阅读(127)  评论(0编辑  收藏  举报