提示
要懂怎么在leetcode上提交
- 注意方法名和类名
- 注意形参名
- 你写的时候是直接输出,与题目要求的返回结果不一致。要修改再提交
List<Integer> ans = new ArrayList<>();
...
ans.add(head.val);
return ans;
先序遍历144
class Solution {
public List<Integer> preorderTraversal(TreeNode head) {
List<Integer> ans = new ArrayList<>();
if(head != null){
Stack<TreeNode> stack = new Stack<TreeNode>();
stack.push(head);
while(!stack.isEmpty()){
head = stack.pop();
ans.add(head.val);
if(head.right != null){
stack.push(head.right);
}
if(head.left != null){
stack.push(head.left);
}
}
}
return ans;
}
}
中序遍历94
class Solution {
public List<Integer> inorderTraversal(TreeNode head) {
List<Integer> ans = new ArrayList<>();
if(head != null){//这个是root
Stack<TreeNode> stack = new Stack();
while(!stack.isEmpty() || head != null){
if(head != null){
//子树左边界全部进栈
stack.push(head);
head = head.left;
}else{
//栈弹出一个节点,打印
//弹出节点为head,对右子树 左边界进栈
head = stack.pop();
ans.add(head.val);
head = head.right;
}
}
}
return ans;
}
}
后序遍历145
class Solution {
public List<Integer> postorderTraversal(TreeNode h) {
List<Integer> ans = new ArrayList<>();
if(h != null){
Stack<TreeNode> stack = new Stack();
stack.push(h);
//如果始终没有打印过节点,h就一直是root头节点
//一旦打印过节点,h就变成打印节点
//之后h的含义:上一次打印的节点
while(!stack.isEmpty()){
TreeNode cur = stack.peek();
if(cur.left != null
&& h != cur.left
&& h != cur.right){
//有左树且左树没处理过
stack.push(cur.left);
}else if(cur.right != null
&& h != cur.right){
//有右树且右树没处理过
stack.push(cur.right);
}else {
//左树,右树都没有 或者 都处理完了
ans.add(cur.val);
h = stack.pop();
}
}
}
return ans;
}
}