LeetCode 二叉树遍历递归实现(前序、中序、后序)

前序遍历

https://leetcode-cn.com/problems/binary-tree-preorder-traversal/description/

1.先访问根节点

2.再访问左子树

3.最后再访问右子树

/**
 * 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 preorderTraversal(TreeNode* root) {
        vector ret;
        inorderTraversal(root, ret);   
        return ret;   
    }
private:
    void preorderTraversal(TreeNode* pNode, vector& ret){
        if(pNode){
            ret.push_back(pNode->val);
            inoderTraversal(pNode->left, ret);
            inoderTraversal(pNode->right, ret);
        }    
    }
};

中序遍历

https://leetcode-cn.com/problems/binary-tree-inorder-traversal/description/

1.先访问左子树

2.再访问根节点

3.最后再访问右子树

/**
 * 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 inorderTraversal(TreeNode* root) {
        vector ret;
        inorderTraversal(root, ret);
        return ret;
    }
private:
    void inorderTraversal(TreeNode* pNode, vector& ret){
        if(pNode){
            inorderTraversal(pNode->left, ret);
            ret.push_back(pNode->val);
            inorderTraversal(pNode->right, ret);
        }
    }
};

后序遍历

https://leetcode-cn.com/problems/binary-tree-postorder-traversal/description/

1.先遍历左子树

2.再遍历右子树

3.最后再遍历根节点

/**
 * 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 postorderTraversal(TreeNode* root) {
        vector ret;
        postoderTraversal(root, ret);
        return ret;
    }
private:
    void postorderTraversal(TreeNode* pNode, vector& ret){
        if(pNode){
            postoderTraversal(pNode->left, ret);
            postoderTraversal(pNode->right,ret);
            ret.push_back(pNode->val);
        }
    }
};

 

你可能感兴趣的:(LeetCode)