二叉树的后序遍历

    xiaoxiao2021-04-14  65

    问题描述:

    给出一棵二叉树,返回其节点值的后序遍历。

    样例

    给出一棵二叉树 {1,#,2,3},

    1 \ 2 / 3

    返回 [3,2,1]

    解题思路:

    用函数调用来写,写一个z后序遍历的函数,用递归的思想,在函数中调用。

    代码:

    /**  * Definition of TreeNode:  * class TreeNode {  * public:  *     int val;  *     TreeNode *left, *right;  *     TreeNode(int val) {  *         this->val = val;  *         this->left = this->right = NULL;  *     }  * }  */ class Solution {     /**      * @param root: The root of binary tree.      * @return: Postorder in vector which contains node values.      */      void postorder(vector<int>&v,TreeNode *root){           if(root==NULL) return ;           postorder(v,root->left);            postorder(v,root->right);           v.push_back(root->val);                 } public:     vector<int> postorderTraversal(TreeNode *root) {          vector<int> v;        postorder(v,root);        return v;         // write your code here     } };

    感悟:

    注意在后序遍历函数中的引用,可以认为是一个全局变量。

    转载请注明原文地址: https://ju.6miu.com/read-670411.html

    最新回复(0)