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

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

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


全部评论

相关推荐

有气魄的马来熊在摸鱼:我爱vivo 马上换手机 vivo我爱你!!!
点赞 评论 收藏
分享
程序员牛肉:继续沉淀吧同学,你这就是纯纯的流水线产品。 差不多的学历+两个烂大街项目。自身学历又不行,现在找啥实习呢。有点太浮躁了。多花点心思搞搞ai,开源和八股。这比你这段时间捣鼓一段小厂实习要好得多;
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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