Binary Tree Postorder Traversal
题目:
Given a binary tree, return the postorder traversal of its nodes' values.
分析:
题目的traversal解法已经通关,送分题,除非不让我用recursion。
解法:
/**
* 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.
*/
public:
void dfs(TreeNode* root, vector<int>& results) {
if (root == NULL) {
return;
}
dfs(root->left, results);
dfs(root->right, results);
results.push_back(root->val);
}
vector<int> postorderTraversal(TreeNode *root) {
// write your code here
if (root == NULL) {
return vector<int>();
}
vector<int> results;
dfs(root, results);
return results;
}
};