[leetcode] Binary Tree Inorder Traversal

Binary Tree Inorder Traversal

使用递归

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

非递归,使用栈模拟

#include <iostream>
#include <vector>
#include <stack>
#include <list>
#include <queue>
using namespace std;

/**
 * Definition for binary tree */
struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
private:
    vector<int> res;
    stack<TreeNode*> stk;
public:
    vector<int> inorderTraversal(TreeNode *root) {
        if (root==NULL) {
            return res;
        }
        stk.push(root);
        while (!stk.empty()) {
            TreeNode *tmp=stk.top();
            if (tmp->left==NULL&&tmp->right==NULL) {
                stk.pop();
                res.push_back(tmp->val);
            }else{
                stk.pop();//通用模板,调整入栈顺序,即可实现先序、中序、后序遍历
                if (tmp->right!=NULL) {
                    stk.push(tmp->right);
                }
                stk.push(tmp);
                if (tmp->left!=NULL) {
                    stk.push(tmp->left);
                }
                tmp->left=tmp->right=NULL;
            }
            
        }
        return res;
    }
};

参考:

Binary Tree Inorder Traversal

你可能感兴趣的:([leetcode] Binary Tree Inorder Traversal)