递归算法的三要素:
1.确定递归函数的参数和返回值
2.确定终止条件
3.确定单层递归的逻辑
144.二叉树的前序遍历
给你二叉树的根节点 root
,返回它节点值的 前序 遍历。
示例 1:
输入:root = [1,null,2,3] 输出:[1,2,3]
递归法
代码参考
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer> ();
preorder(root,list);
return list;
}
public void preorder(TreeNode t,List<Integer> list){
//终止条件
if(t==null){
return;
}
list.add(t.val);
preorder(t.left,list);
preorder(t.right,list);
}
}
中序遍历:
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer>list=new ArrayList<>();
inOrder(root,list);
return list;
}
public void inOrder(TreeNode root,List<Integer>list){
if(root==null){
return;
}
inOrder(root.left,list);
list.add(root.val);
inOrder(root.right,list);
}
}
后序遍历:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer>list=new ArrayList<>();
postOrder(root,list);
return list;
}
public void postOrder(TreeNode root,List<Integer> list){
if(root==null){
return;
}
postOrder(root.left,list);
postOrder(root.right,list);
list.add(root.val);
}
}
迭代法
先序遍历:栈中要先加入右孩子再加入左孩子
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list=new ArrayList<Integer> ();
Stack<TreeNode>stack = new Stack<>();
//判断root是否为空
if(root==null)return list;
//将根节点加入
stack.push(root);
while(!stack.empty()){
//栈中弹出一个结点
TreeNode t= stack.pop();
if(t!=null){
list.add(t.val);
stack.push(t.right);
stack.push(t.left);
}
}
return list;
}
}
中序遍历:借用指针的遍历来帮助访问节点,栈则用来处理节点上的元素。
class Solution {
public List<Integer> inorderTraversal(TreeNode root) {
List<Integer>list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
TreeNode cur=root;
while(cur!=null||!stack.empty()){
if(cur!=null){
//结点不为空,就压栈,让cur=cur.left
stack.push(cur);
cur=cur.left;
}else{
//结点为空,栈中取出上一层的中结点,让cur=cur.right作为新的结点;
cur=stack.pop();
list.add(cur.val);
cur=cur.right;
}
}
return list;
}
}
后序遍历:
class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
List<Integer>list=new ArrayList<>();
Stack<TreeNode> stack=new Stack<>();
if(root==null){
return list;
}
stack.push(root);
while(!stack.empty()){
TreeNode t= stack.pop();
if(t!=null){
list.add(t.val);
stack.push(t.left);
stack.push(t.right);
}
}
Collections.reverse(list);
return list;
}
}