本文主要是介绍LeetCode 145 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?
题目链接:https://leetcode.com/problems/binary-tree-postorder-traversal/
递归:
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
public class Solution {public void DFS(TreeNode root, List<Integer> ans) {if(root == null) {return;}DFS(root.left, ans);DFS(root.right, ans);ans.add(root.val);}public List<Integer> postorderTraversal(TreeNode root) {List<Integer> ans = new ArrayList<>();DFS(root, ans);return ans;}
}
非递归:后序遍历左右中,考虑到栈的先进先出,故先将右子树压栈,两种情况记录答案出栈,1是遇到叶子,2是父节点的子节点已经被访问过,根据压栈顺序,可以保证这样可以完成后序遍历
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode(int x) { val = x; }* }*/
public class Solution {public List<Integer> postorderTraversal(TreeNode root) {List<Integer> ans = new ArrayList<>();Stack<TreeNode> stk = new Stack<>();if(root != null) {stk.push(root);}TreeNode cur = null;TreeNode pre = null;while(!stk.empty()) {cur = stk.peek();if(cur.left == null && cur.right == null) {ans.add(cur.val);pre = cur;stk.pop();}else if(pre != null && (cur.left == pre || cur.right == pre)) {ans.add(cur.val);pre = cur;stk.pop();}else {if(cur.right != null) {stk.push(cur.right);}if(cur.left != null) {stk.push(cur.left);}}}return ans;}
}
这篇关于LeetCode 145 Binary Tree Postorder Traversal (后序遍历二叉树)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!