• 周四. 10 月 3rd, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Leetcode 145: postorder traversal of binary tree (Java)

King Wang

1 月 3, 2022

LeetCode 145: Postorder traversal of binary trees (java)

subject :

answer :

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
/*
class Solution {
List<Integer> list=new ArrayList<>();
public List<Integer> postorderTraversal(TreeNode root) {
if(root!=null){
postorderTraversal(root.left);
postorderTraversal(root.right);
list.add(root.val);
}
return list;
}
}*/
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<>();
Stack<TreeNode> nodeStack=new Stack<>();
TreeNode nodeTemp=root;
TreeNode preNode=null;
while(nodeTemp!=null || !nodeStack.isEmpty()){
while(nodeTemp!=null){
nodeStack.push(nodeTemp);
nodeTemp=nodeTemp.left;
}
nodeTemp=nodeStack.peek();
if(nodeTemp.right==null || nodeTemp.right==preNode){
nodeTemp=nodeStack.pop();
list.add(nodeTemp.val);
preNode=nodeTemp;
nodeTemp=null;
}else{
nodeTemp=nodeTemp.right;
}
}
return list;
}
}

 

发表回复