本文主要是介绍leetcode--Binary Tree Postorder Traversal,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述:
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?
二叉树的后序遍历
递归算法:
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int>res;if(root==NULL) return res;return postorder(root,res);}vector<int> postorder(TreeNode* root,vector<int>& res){if(root){postorder(root->left,res);postorder(root->right,res);res.push_back(root->val);}return res;}
};
迭代算法:
class Solution {
public:vector<int> postorderTraversal(TreeNode* root) {vector<int>res;if(root==NULL) return res;stack<TreeNode*> qu;TreeNode* node=root;while(!qu.empty()||node){if(node){qu.push(node);res.push_back(node->val);node=node->right;}else{TreeNode* cur=qu.top();qu.pop();node=cur->left;}}reverse(res.begin(),res.end());return res;}
};
总结
这篇关于leetcode--Binary Tree Postorder Traversal的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!