力扣-94-二叉树的中序遍历

题目:传送门

方法一、递归

中序遍历:先遍历左子树,在遍历根节点,最后遍历右子树。比较经典的方法是递归。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <vector>
using namespace std;

class Solution {
public:
    void dfs(vector<int>& res, TreeNode* root){
        if(root == NULL) return ;
        dfs(res, root->left);
        res.push_back(root->val);
        dfs(res, root->right);
    }
    
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> result;
        dfs(result, root);
        return result;
    }
};

 方法二、使用栈进行中序遍历

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
/*方法二、使用栈的中序遍历*/
#include <vector>
#include <stack>
using namespace std;
class Solution {
public:
    vector<int> inorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode* > Stack;
        TreeNode* curr = root;
        while(curr != NULL || !Stack.empty()){
            while(curr != NULL) {//找左子树,并压入堆栈
                Stack.push(curr);
                curr = curr->left; 
            }
            curr = Stack.top();//top()返回栈顶元素,但是不删除;
            Stack.pop();//pop()删除栈顶元素,但是不返回
            res.push_back(curr->val);
            curr = curr->right;
        }
        return res;
    }
};

 

posted @ 2020-07-26 08:41  Peterxiazhen  阅读(143)  评论(0编辑  收藏  举报