java二叉树遍历递归和非递归_【Java】二叉树的遍历总结(递归与非递归)

二叉树的前序遍历

递归:

public ArrayList postorder(TreeNode root) {

ArrayList res = new ArrayList();

//采用递归方式

if (root==null)

return res;

if (root!=null)

res.add(root.val);

if (root.left!=null)

postorderTraversal(root.left);

if (root.right!=null)

postorderTraversal(root.right);

return res;

}

非递归:

ArrayList res = new ArrayList();

public ArrayList preorderTraversal(TreeNode root) {

//采用非递归方式:用到栈,先右子树进栈,后左子树进栈

Stack stack = new Stack();

if (root == null)

return res;

if (root !=null){

stack.push(root);

while(!stack.isEmpty()){

TreeNode n =stack.pop();

res.add(n.val);

if (n.right!=null)

stack.push(n.right);

if (n.left != null)

stack.push(n.left);

}

}

return res;

}

}

二叉树的中序遍历

递归:

public ArrayList inorder(TreeNode root) {

ArrayList res = new ArrayList();

//采用递归方式

if (root==null)

return res;

if (root.left!=null)

postorderTraversal(root.left);

res.add(root.val);

if (root.right!=null)

postorderTraversal(root.right);

return res;

}

非递归:

public ArrayList inorder(TreeNode root) {

ArrayList res = new ArrayList<>();

if(root == null) {

return res;

}

Stack stack = new Stack<>();

TreeNode p = root;

while(p != null || !stack.isEmpty()) {

if(p != null) {

stack.push(p);

p = p.left;

} else {

p = stack.pop();

res.add(p.val);

p = p.right;

}

}

return res;

}

二叉树的后序遍历

递归:

public ArrayList postorder(TreeNode root) {

ArrayList res = new ArrayList();

//采用递归方式

if (root==null)

return res;

if (root.left!=null)

postorderTraversal(root.left);

if (root.right!=null)

postorderTraversal(root.right);

res.add(root.val);

return res;

}

非递归:

//!!!不要忘记导对应的包

public ArrayList postorder(TreeNode root) {

ArrayList res = new ArrayList();

//非递归方式:

if (root==null)

return res;

Stack stack = new Stack();

TreeNode p = root;

TreeNode r = null;

while(p != null || !stack.isEmpty()){

if (p !=null){

stack.push(p);

p = p.left; //所有左孩子入栈,直到左孩子为空

}

else{

p = stack.peek();

p = p.right; //若果没有节点没有左孩子,访问栈顶元素的右孩子

if(p !=null && p !=r){

stack.push(p); //若果有右孩子,就让其顺延所有的左孩子入栈

p=p.left;

}else{

p=stack.pop(); //若果没有右孩子,就把就出栈,访问,

res.add(p.val);

r=p; //r记录刚访问的节点

p=null; //把p置空,就可以继续访问栈顶元素

}

}

}

return res;

}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值