您的位置:首页 > 其它

LeetCode Everyday-- 94,144,145递归解法

2015-08-08 11:36 246 查看

Binary Tree Inorder Traversal

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

For example:

Given binary tree {1,#,2,3},

1

\

2

/

3

return [1,3,2].

三个题目类似,我就放在一起,分别是树的先序遍历,中序遍历和后序遍历。递归解法是非常简单的,也可以AC。

但是题目中有一句话Note: Recursive solution is trivial, could you do it iteratively? 最近递归用多了,迭代都不会用了,有时间再想想迭代的方法。

[code]/**
 * 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> v;
        travel(root,v);
        return v;
    }

private:
    void travel(TreeNode* root,vector<int> &v){

        if(root == NULL){
            return ;
        }
       //先序遍历
        //v.push_back(root->val);
        travel(root->left,v);
        //中序遍历
        v.push_back(root->val);
        travel(root->right,v);
        //后序遍历
        //v.push_back(root->val);
    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: