# leetCode解题报告之Binary Tree Postorder Traversal

26 篇文章 0 订阅
26 篇文章 3 订阅

### 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?

2、我们判断下它的left（node.left）是否为null,如果不为null，把它的左孩子结点push到栈中来，并把它的左孩子域设为null, 然后跳过此次循环剩下的部分

3、如果它的left 为null, 把它的右孩子结点push到栈中来，并把它的右孩子域设为null，然后跳过此次循环剩下的部分！

package cn.xym.leetcode.binarytree;

import java.util.ArrayList;
import java.util.Stack;

class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}
}
public class Solution {

public ArrayList<Integer> postorderTraversal(TreeNode root) {
if (root == null)
return null;
ArrayList<Integer> list = new ArrayList<Integer>();
Stack<TreeNode> stack = new Stack<TreeNode>();
//先把最后访问的结点先放入到栈中，即根节点root
stack.push(root);
while (stack.size() != 0){
TreeNode top = stack.peek();
if (top.left == null && top.right == null){
stack.pop();
}
if (top.left != null){
stack.push(top.left);
top.left = null;
continue;
}
if (top.right != null){
stack.push(top.right);
top.right = null;
continue;
}
}
return list;
}
}


### Binary Tree Preorder Traversal

Given a binary tree, return the preorder traversal of its nodes' values.

For example:
Given binary tree {1,#,2,3},

   1
\
2
/
3


return [1,2,3].

Note: Recursive solution is trivial, could you do it iteratively?

AC代码：

package cn.xym.leetcode.binarytree;

import java.util.ArrayList;
import java.util.Stack;

class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}
}
public class Solution {

public ArrayList<Integer> preorderTraversal(TreeNode root) {

ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<Integer> list2 = new ArrayList<Integer>();
if (root == null)
return list;
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(root);
while (stack.size() != 0){
TreeNode top = stack.peek();
if (top.left == null && top.right == null){
stack.pop();
}
if (top.right != null){
stack.push(top.right);
top.right = null;
continue;
}
if (top.left != null){
stack.push(top.left);
top.left = null;
continue;
}
}
for (int i=0; i<list.size(); ++i){
}
return list2;
}
public static void main(String[] args) {
Solution sl = new Solution();
TreeNode root1 = new TreeNode(1);
TreeNode root2 = new TreeNode(2);
TreeNode root3 = new TreeNode(3);
TreeNode root4 = new TreeNode(4);
TreeNode root5 = new TreeNode(5);
TreeNode root6 = new TreeNode(6);
root1.left = root2;
root1.right = root3;
root2.left = root4;
root2.right = root5;
root3.left = root6;

ArrayList<Integer> list = sl.preorderTraversal(root1);
System.out.println(list);
}
}


• 0
点赞
• 0
收藏
觉得还不错? 一键收藏
• 打赏
• 0
评论
03-26 228
08-13 395

### “相关推荐”对你有帮助么？

• 非常没帮助
• 没帮助
• 一般
• 有帮助
• 非常有帮助

¥2 ¥4 ¥6 ¥10 ¥20

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。