[Leetcode]94. Binary Tree Inorder Traversal

94. Binary Tree Inorder Traversal

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?
题意:二叉树的中序遍历,要求用迭代
思路:使用到栈,将整棵树的最左边的一条链压入栈中,每次取出栈顶元素,如果它有右子树,则将右子树压入栈中。

/**
 * 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;
        stack<TreeNode*> stk;
        auto p=root;
        while(p||stk.size())
        {
            while(p)//整颗子树的最左侧进栈
            {
                stk.push(p);
                p=p->left;
            }
            p=stk.top();
            stk.pop();
            res.push_back(p->val);
            p=p->right;
        }
        return res;
    }
};

给出递归写法

/**
 * 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> result;
        inorder(root,result);
        return result;
    }
        void inorder(TreeNode* root,vector<int>& v){
            if(root!=nullptr){
                inorder(root->left,v);
                v.push_back(root->val);
                inorder(root->right,v);
            }
        }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容