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

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

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 pre_order(TreeNode* root,vector<int>& result){
        if(root==nullptr) return;
        result.push_back(root->val);
        pre_order(root->left, result);
        pre_order(root->right, result);
    }
    
    void in_order(TreeNode* root,vector<int>& result){
        if(root==nullptr) return;
        in_order(root->left, result);
        result.push_back(root->val);
        in_order(root->right, result);
    }
    
    void post_order(TreeNode* root,vector<int>& result){
        if(root==nullptr) return;
        post_order(root->left, result);
        post_order(root->right, result);
        result.push_back(root->val);
    }
    
    vector<vector<int> > threeOrders(TreeNode* root) {
        // write code here
        vector<vector<int>> result{};
        vector<int> pre_result{};
        vector<int> in_result{};
        vector<int> post_result{};
        
        pre_order(root, pre_result);
        in_order(root, in_result);
        post_order(root,post_result);
        
        result.push_back(pre_result);
        result.push_back(in_result);
        result.push_back(post_result);
        
        return result;
    }
};


全部评论

相关推荐

只有一个苍穹外卖外加正在看黑马点评,可以找小厂实习吗,还有我的简历有什么大问题吗
Java抽象小篮子:感觉有点熟悉,问题1是学历,2是没实习经历,3是专业技能写得太少太少了(怎么写可以看我置顶帖),4是仅这一个项目找实习不够看。拷打完毕,简历怎么写可以看我置顶帖子
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务