二叉树层序遍历递归与非递归_总结归纳:二叉树遍历【递归 && 非递归】...

今天为大家总结了二叉树前中后序遍历的递归与迭代解法:

1. 前序遍历

递归
List list=new ArrayList<>();public ListpreOrder(TreeNode root ){if(root == null)return list;
list.add(root.val);
preOrder(root.left);
preOrder(root.right);return list;
}
非递归
public ListpreOrder2(TreeNode root){
if(root==null)
return new ArrayList<>();
List list = new ArrayList<>();
Stack stack = new Stack<>();
stack.push(root);while (!stack.isEmpty()){
TreeNode tmp = stack.pop();
list.add(tmp.val);if(tmp.right!=null)
stack.push(tmp.right);if(tmp.left!=null)
stack.push(tmp.left);
}return list;
}

2. 中序遍历

递归
List list=new ArrayList<>();public ListinOrder(TreeNode root ){if(root == null)return list;
inOrder(root.left);
list.add(root.val);
inOrder(root.right);return list;
}
非递归
public ListinOrder2(TreeNode root) {
List list = new ArrayList<>();
Stack stack = new Stack<>();
TreeNode cur = root;while(cur!=null || !stack.empty()){while(cur!=null){
stack.add(cur);
cur = cur.left;
}
cur = stack.pop();
list.add(cur.val);
cur = cur.right;
}return list;
}

3. 后序遍历

递归
public ListpostOrder(TreeNode root ){
if(root == null)
return list;
postOrder(root.left);
postOrder(root.right);
list.add(root.val);
return list;
}
非递归一
public ListpostOrder2(TreeNode root){
if(root == null)
return new ArrayList<>();
List list = new ArrayList<>();
Stack stack = new Stack<>();
stack.push(root);while (!stack.isEmpty()){
TreeNode tmp = stack.pop();
list.add(tmp.val);if(tmp.left!=null)
stack.push(tmp.left);if(tmp.right!=null)
stack.push(tmp.right);
}
Collections.reverse(list);return list;
}
非递归二
public ListpostOrder3(TreeNode root) {
List ans = new ArrayList<>();
Stack stack = new Stack<>();
TreeNode cur = root;while (!stack.isEmpty() || cur != null) {if (cur != null && cur.left != null) {
stack.push(cur);
TreeNode left = cur.left;
cur.left = null;
cur = left;
} else if (cur != null && cur.right != null) {
stack.push(cur);
TreeNode right = cur.right;
cur.right = null;
cur = right;
} else if (cur.left == null && cur.right == null) {
ans.add(cur.val);
cur = stack.isEmpty() ? null : stack.pop();
}
}return ans;
}

关注微信公众号“算法岗从零到无穷”,更多算法知识点告诉你。

6e87ada952abd0323a54891fd542ff2a.png
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值