首页 > 代码库 > [LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历
[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?
经典题目,求二叉树的后序遍历的非递归方法,跟前序,中序,层序一样都需要用到栈,后续的顺序是左-右-根,所以当一个节点值被取出来时,它的左右子节点要么不存在,要么已经被访问过了。具体思路可参见神网友 Yu‘s Coding Garden 的博客,代码如下:
/** * Definition for binary tree * 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> res; if (!root) return res; stack<TreeNode*> s; s.push(root); TreeNode *head = root; while (!s.empty()) { TreeNode *top = s.top(); if ((!top->left && !top->right) || top->left == head || top->right == head) { res.push_back(top->val); s.pop(); head = top; } else { if (top->right) s.push(top->right); if (top->left) s.push(top->left); } } return res; }};
[LeetCode] Binary Tree Postorder Traversal 二叉树的后序遍历
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。