Binary Tree Postorder Traversal

来源:互联网 发布:手机怎么上电脑版淘宝 编辑:程序博客网 时间:2024/05/17 17:44

一、问题描述

Given a binary tree, return the postorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1    \     2    /   3

return [3,2,1].

二、思路

二叉树的后续遍历,非递归遍历稍微复杂一点,需要另外设置一个数据结构,改天补上,未完待续。

三、代码

/** * 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:    void postorder(TreeNode* node,vector<int> &res){        if(!node){            return ;        }else{            postorder(node -> left,res);            postorder(node -> right,res);            res.push_back(node -> val);        }    }    vector<int> postorderTraversal(TreeNode* root) {        vector<int> vec;        postorder(root,vec);        return vec;    }};


0 0
原创粉丝点击