Leetcode:145. 二叉树的后序遍历

给定一个二叉树,返回它的 后序 遍历。

示例:

输入: [1,null,2,3]  
   1
    \
     2
    /
   3 

输出: [3,2,1]

解题思路:

后序遍历:1. 左子树。2.右子树。3.根节点。

                                                

C++代码
#define hasLChild(x) (!(x->left==NULL))
#define hasRChild(x) (!(x->right==NULL))
class Solution {
public:
    vector<int> postorderTraversal(TreeNode* root) {
        if (root == NULL) return{};
        DFS(root);
        return res;
    }
    void DFS(TreeNode* root) {
        if (root == NULL) return;
        if (hasLChild(root)) DFS(root->left);
        if (hasRChild(root)) DFS(root->right);
        res.push_back(root->val);
    }
private:
    vector<int> res;
};

猜你喜欢

转载自blog.csdn.net/qq_23523409/article/details/83755266