94. Binary Tree Inorder Traversal 二叉树中序遍历

题目链接
tag:

  • Medium;
  • Stack;

question:
  Given a binary tree, return the inorder traversal of its nodes' values.

Example:

Input: [1,null,2,3]
1
\
2
/
3
Output: [1,3,2]
Follow up: Recursive solution is trivial, could you do it iteratively?

C++ 解法一:
思路:
  二叉树的中序遍历顺序为左-根-右,可以有递归和非递归来解。我们先来看递归方法,十分直接,对左子结点调用递归函数,根节点访问值,右子节点再调用递归函数,代码如下:

/**
 * 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 inorderTraversal(TreeNode* root) {
        vector res;
        inorder(root, res);
        return res;
    }
    
    void inorder(TreeNode* root, vector &res) {
        if (!root) return;
        if (root->left)
            inorder(root->left, res);
        res.push_back(root->val);
        if (root->right)
            inorder(root->right, res);
    }
};

C++ 解法二:
思路:
  非递归使用栈的解法,也是符合本题要求使用的解法,思路是从根节点开始,先将根节点压入栈,然后再将其所有左子结点压入栈,然后取出栈顶节点,保存节点值,再将当前指针移到其右子节点上,若存在右子节点,则在下次循环时又可将其所有左子结点压入栈中。这样就保证了访问顺序为左-根-右,代码如下:

/**
 * 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 inorderTraversal(TreeNode* root) {
        // Non-recursion
        vector res;
        stack sk;
        TreeNode *p = root;
        while (p || !sk.empty()) {
            while (p) {
                sk.push(p);
                p = p->left;
            }
            p = sk.top();
            sk.pop();
            res.push_back(p->val);
            p = p->right;
        }
        return res;
    }
};

C++ 解法三:模板形式

class Solution {
public:
    vector inorderTraversal(TreeNode* root) {
        vector res;
        stack s;
        TreeNode *p = root;
        while (!s.empty() || p) {
            if (p) {
                s.push(p);
                p = p->left;
            } else {
                p = s.top(); s.pop();
                res.push_back(p->val);
                p = p->right;
            }
        }
        return res;
    }
};

你可能感兴趣的:(94. Binary Tree Inorder Traversal 二叉树中序遍历)