题解 | #实现二叉树先序,中序和后序遍历#

实现二叉树先序,中序和后序遍历

http://www.nowcoder.com/practice/a9fec6c46a684ad5a3abd4e365a9d362

/**
 * struct TreeNode {
 *    int val;
 *    struct TreeNode *left;
 *    struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 the root of binary tree
     * @return int整型vector<vector<>>
     */
    void preOrder(TreeNode* root,vector<int>& ret)
    {
        if (!root) {
            return;
        }
        ret.push_back(root->val);
        preOrder(root->left,ret);
        preOrder(root->right,ret);
    }

    void inOrder(TreeNode* root,vector<int>& ret)
    {
        if (!root) {
            return;
        }

        inOrder(root->left,ret);
        ret.push_back(root->val);
        inOrder(root->right,ret);
    }

    void nextOrder(TreeNode* root,vector<int>& ret)
    {
        if (!root) {
            return;
        }
        nextOrder(root->left,ret);
        nextOrder(root->right,ret);
        ret.push_back(root->val);
    }

    vector<vector<int> > threeOrders(TreeNode* root) {
        vector<int> ret1;
        vector<int> ret2;
        vector<int> ret3;
        preOrder(root,ret1);
        inOrder(root,ret2);
        nextOrder(root,ret3);
        vector<vector<int> > ret;
        ret.push_back(ret1);
        ret.push_back(ret2);
        ret.push_back(ret3);
        return ret;
    }
};
全部评论

相关推荐

11-15 18:39
已编辑
西安交通大学 Java
全村最靓的仔仔:卧槽,佬啥bg呢,本也是西交么
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务