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

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

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;
    }
};


全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务