美文网首页
94.binary-tree-inorder-traversa

94.binary-tree-inorder-traversa

作者: Optimization | 来源:发表于2020-05-08 08:33 被阅读0次

    题目:

    94.binary-tree-inorder-traversa

    解答:

    迭代方法:

    /**
     * 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) {
            if(root == nullptr) return {};
            TreeNode* curNode = root;
            stack<TreeNode*> s;
            vector<int> ans;
            while(curNode != nullptr || !s.empty()){
                while(curNode != nullptr){
                    s.push(curNode);
                    curNode = curNode->left;
                }
                curNode = s.top();s.pop();
                ans.push_back(curNode->val);
                curNode = curNode->right;
            }
            return ans;
        }
    };
    
    递归方法:

    关键是构造一个辅助函数

    /**
     * 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> ans;
            inorderTraversal(root,ans);
            return ans;
        }
    private:
        void inorderTraversal(TreeNode* root,vector<int>& ans){
            // 递归终止条件
            if(root == NULL) return;
            // 先访问左子树,再访问根节点,再访问右子树
            inorderTraversal(root->left, ans);
            ans.push_back(root->val);
            inorderTraversal(root->right,ans);
        }
    };
    

    相关文章

      网友评论

          本文标题:94.binary-tree-inorder-traversa

          本文链接:https://www.haomeiwen.com/subject/mynamhtx.html