码迷,mamicode.com
首页 > 其他好文 > 详细

LintCode 68. 二叉树的后序遍历

时间:2018-01-27 11:20:07      阅读:149      评论:0      收藏:0      [点我收藏+]

标签:back   contain   problem   nbsp   ref   array   amp   tor   nta   

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

 

样例

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

   1
         2
    /
   3

返回 [3,2,1]

挑战 

你能使用非递归实现么?

 

解:递归解,非递归以后补充

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */


class Solution {
public:
    /*
     * @param root: A Tree
     * @return: Postorder in ArrayList which contains node values.
     */
    vector<int> postorderTraversal(TreeNode * root) {
        // write your code here
        vector<int> re;
        if(root!=NULL)
        {
            postorder(root,re);
        }
        return re;
    }
    void postorder(TreeNode* node,vector<int> &re)
    {
        if(node==NULL)
            return;
        if(node->left!=NULL)
            postorder(node->left,re);
        if(node->right!=NULL)
            postorder(node->right,re);
        re.push_back(node->val);
    }
};

 

LintCode 68. 二叉树的后序遍历

标签:back   contain   problem   nbsp   ref   array   amp   tor   nta   

原文地址:https://www.cnblogs.com/zslhg903/p/8362104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!