Leetcode Binary Tree Postorder Traversal

来源:互联网 发布:mac如何隐藏菜单栏 编辑:程序博客网 时间:2024/05/22 14:50

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].

Note: Recursive solution is trivial, could you do it iteratively?


递归大法代码如下:

/** * 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<int> postorderTraversal(TreeNode* root) {        vector<int> result;          postorder(root,result);          return result;    }        void postorder(TreeNode* root,vector<int>& result)      {          if(root == NULL)              return;          postorder(root->left,result);          postorder(root->right,result);          result.push_back(root->val);      }  };

迭代大法代码如下:


原创粉丝点击