Leetcode--145. 二叉树的后序遍历(迭代递归)
給定一個二叉樹,返回它的 后序?遍歷。
示例:
輸入: [1,null,2,3] ?
? ?1
? ? \
? ? ?2
? ? /
? ?3?
輸出: [3,2,1]
代碼:
迭代:
從根節點開始依次迭代,彈出棧頂元素輸出到輸出列表中,然后依次壓入它的所有孩子節點,按照從上到下、從左至右的順序依次壓入棧中。
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????public?List<Integer>?postorderTraversal(TreeNode?root)?{
????????List<Integer>?result?=?new?LinkedList<>();
????????Stack<TreeNode>?stack?=?new?Stack<>();
????????if(root==null){
????????????return?result;
????????}
????????stack.add(root);
????????while(!stack.isEmpty()){
????????????TreeNode?temp?=?stack.pop();
????????????result.add(0,temp.val);
????????????if(temp.left!=null){
????????????????stack.add(temp.left);
????????????}
????????????if(temp.right!=null){
????????????????stack.add(temp.right);
????????????}
????????}
????????return?result;
????}
}
?
遞歸:
/**
?*?Definition?for?a?binary?tree?node.
?*?public?class?TreeNode?{
?*?????int?val;
?*?????TreeNode?left;
?*?????TreeNode?right;
?*?????TreeNode(int?x)?{?val?=?x;?}
?*?}
?*/
class?Solution?{
????List<Integer>?result?=?new?LinkedList<>();
????public?List<Integer>?postorderTraversal(TreeNode?root)?{
????????
????????if(root==null){
????????????return?result;
????????}
????????helper(root);
????????return?result;
????}
????public?void?helper(TreeNode?root){
????????if(root==null){
????????????return;
????????}
????????helper(root.left);
????????helper(root.right);
????????result.add(root.val);
????}
}
總結
以上是生活随笔為你收集整理的Leetcode--145. 二叉树的后序遍历(迭代递归)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【剑指 offer】面试题13:机器人的
- 下一篇: RequestMapping注解的继承问