一周算法总结

一、二叉树的深度优先遍历,包括递归和非递归

(一)针对递归的方式,因为树的结点在遍历时,每个节点会访问三次,因此在第几次打印决定了是先、中还是后序
基本操作:
  	System.out.println(head.val +" ");
    preOrderRecur(head.left);
    preOrderRecur(head.right);

(二)非递归的方式,深度优先遍历采用栈的操作
	 1、先序:当前栈不空,先压右孩子再压左孩子
	 Code如下:
	    public static void preOrderUnRecur(TreeNode head){
	        if(head!=null){
	            Stack<TreeNode> stack = new Stack();
	            stack.push(head);
	            while(!stack.isEmpty()){
	                head = stack.pop();
	                System.out.println(head);
	                if(head.right!=null){
	                    stack.push(head.right);
	                }
	                if(head.left!=null){
	                    stack.push(head.right);
	  2、中序:中序非递归
 * 当前节点不为NULL则压栈,并移动到其左孩子
 * 当前节点为空则弹栈,并移动到其右孩子
 *//*

public static void inOrderUnRecur(TreeNode head){
    if(head!=null){
        Stack<TreeNode> stack = new Stack<>();
        stack.push(head);
        while(!stack.isEmpty()||head!=null){
            if(head!=null){
                stack.push(head);
                head=head.left;
            }else{
                head = stack.pop();
                System.out.println(head.val);
                head = head.right;
	 3、 后序
 * 先序是中左右   中右左也很好实现
 * 而 中右左 的逆序 就是左右中  即后序
 *//*

public static void posOrderUnRecur(TreeNode head){
    if(head!=null){
        Stack<TreeNode> s1 = new Stack<>();
        s1.push(head);
        Stack<TreeNode> s2 = new Stack<>();
        while(!s1.isEmpty()){
            head = s1.pop();
            s2.push(head);
            if(head.left!=null){
                s1.push(head.left);
            }
            if(head.right!=null){
                s1.push(head.right);
            }
        }
        while(!s2.isEmpty()){
            System.out.print(s2.pop().val +" ");

二、二叉树的序列化和反序列化

这块注意一点就是怎么序列化的(如你是先序序列化的)就怎么反序列化(先序反序列化)
具体的可以看https://leetcode-cn.com/problems/xu-lie-hua-er-cha-shu-lcof/

三、关于线索二叉树

线索二叉树的中序遍历是升序

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值