Binary Tree Postorder Traversal
程序员文章站
2022-05-20 13:52:14
...
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].
输出一颗树的后序遍历序列。我们可以用递归和迭代两种方法。用迭代时我们借助堆栈,因为是后序遍历,顺序为左-右-根,因此我们只需要通过根-右-左的顺序进行遍历,然后将序列翻转就可以了。代码如下:
递归:
迭代:
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [3,2,1].
输出一颗树的后序遍历序列。我们可以用递归和迭代两种方法。用迭代时我们借助堆栈,因为是后序遍历,顺序为左-右-根,因此我们只需要通过根-右-左的顺序进行遍历,然后将序列翻转就可以了。代码如下:
递归:
/**
* 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> list = new ArrayList<Integer>();
if(root == null) return list;
getPostorder(root, list);
return list;
}
public void getPostorder(TreeNode root, List<Integer> list) {
if(root == null) return;
getPostorder(root.left, list);
getPostorder(root.right, list);
list.add(root.val);
}
}
迭代:
/**
* 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) {
LinkedList<Integer> list = new LinkedList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
if(root == null) return list;
stack.add(root);
while(!stack.isEmpty()) {
TreeNode node = stack.pop();
list.addFirst(node.val);
if(node.left != null) {
stack.push(node.left);
}
if(node.right != null) {
stack.push(node.right);
}
}
return list;
}
}
推荐阅读
-
LC 297 Serialize and Deserialize Binary Tree
-
leetcode笔记:Invert Binary Tree
-
Convert Sorted Array to Binary Search Tree
-
minimum-depth-of-binary-tree
-
cf438E. The Child and Binary Tree(生成函数 多项式开根 多项式求逆)
-
【leetcode】-700. Search in a Binary Search Tree 查找二叉搜索树
-
Leetcode——108. Convert Sorted Array to Binary Search Tree
-
Leetcode 108. Convert Sorted Array to Binary Search Tree
-
21天刷题计划之17.1—maximum-depth-of-binary-tree(二叉树的最大深度)(Java语言描述)
-
21天刷题计划之18.1—balanced-binary-tree(平衡二叉树)(Java语言描述)