【To Understand!】LeetCode 94. Binary Tree Inorder Traversal

LeetCode 94. Binary Tree Inorder Traversal

Solution1:递归版
二叉树的中序遍历递归版是很简单的,关键是迭代版的代码既难理解又难写!
迭代版链接:https://blog.csdn.net/allenlzcoder/article/details/79837841

/**
 * 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> res;
        my_Inordertraversal(root, res);
        return res;
    }

    void my_Inordertraversal(TreeNode* root, vector<int>& res) {
        if (root)
            my_Inordertraversal(root->left, res);
        if (!root) return;
        res.push_back(root->val);
        if (root)
            my_Inordertraversal(root->right, res);
    }
};

Solution2:迭代版
1.申请一个栈,头结点为开始节点(当前节点)
2.如果当前节点不为空,那么将左节点压栈,即做cur = cur->left操作,如果当前节点为空的时候打印栈顶元素,并且出栈,将 当前节点变为栈顶元素的右节点也就是做cur = temp->right(中序遍历中,栈主要保存的是父节点元素)
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> inorderTraversal(TreeNode* root) {
        vector<int> res;
        if (!root) return res;
        TreeNode* cur = root;
        stack<TreeNode*> my_stack;
        while(!my_stack.empty() || cur != NULL) {
            if(cur == NULL) {
                TreeNode* temp = my_stack.top();
                my_stack.pop();
                res.push_back(temp->val);
                cur = temp->right;
            } else {
                my_stack.push(cur);
                cur = cur->left;
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/allenlzcoder/article/details/80722193