【二叉树经典问题】94. Binary Tree Inorder Traversal

来源:互联网 发布:指南针软件怎么使用 编辑:程序博客网 时间:2024/05/21 06:22

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

For example:
Given binary tree [1,null,2,3],

   1    \     2    /   3

return [1,3,2].

Note: 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;        if(!root) return res;        inorderTraversal(root->left);        res.push_back(root->val);        inorderTraversal(root->right);        return res;    }};
错误的原因是,在递归调用的过程中每一次都新建了vector<int> res,调用结束就被销毁了,所以最后只能得到最后返回那一步的res,这个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> res;        //if(!root) return res;        inorder(root,res);        return res;    }    void inorder(TreeNode* &root,vector<int>& res){        if(!root) return;        inorder(root->left,res);        res.push_back(root->val);        inorder(root->right,res);    }};

非递归:

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







阅读全文
0 0
原创粉丝点击