二叉树相关算法


🚀 动画演示:数据结构简记✏️ | 二叉树遍历&图遍历(动画演示)

⭐节点定义

class TreeNode {
     int val;
     TreeNode left;
     TreeNode right;
     public TreeNode(int val) {
         this.val = val;
     }
 }

⭐遍历

1 先序遍历

🚀 递归

public void preOrder(TreeNode root) {
	if (null != root) {
	    System.out.println(root.val);
	    preOrder(root.left);
	    preOrder(root.right);
	}
}

🚀 非递归

public void preOrder(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
	// 根节点先压栈
    stack.push(root);
    while (! stack.isEmpty()) {
        TreeNode topNode = stack.pop();
        System.out.println(topNode.val);
        // 先压入右节点,出栈时就会先弹出左节点
        if (null != topNode.right) {
            stack.push(topNode.right);
        }
        if (null != topNode.left) {
            stack.push(topNode.left);
        }
    }
}

2 中序遍历

🚀 递归

public void inOrder(TreeNode root) {
	if (null != root) {
	    inOrder(root.left);
	    System.out.println(root.val);
	    inOrder(root.right);
	}
}

🚀 非递归

public void inOrder(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
    TreeNode currNode = root;

    while (! stack.isEmpty() || null != currNode) {
        // 将全部左节点依次压栈
        while (null != currNode) {
            stack.push(currNode);
            currNode = currNode.left;
        }

        // 弹出此时的栈顶节点
        TreeNode topNode = stack.pop();
        System.out.println(topNode.val);

        // 当前节点更新为栈顶节点的右节点
        currNode = topNode.right;
    }
}

3 后序遍历

🚀 递归

public void postOrder(TreeNode root) {
	if (null != root) {
	    postOrder(root.left);
	    postOrder(root.right);
	    System.out.println(root.val);
	}
}

🚀 非递归

public void postOrder(TreeNode root) {
    LinkedList<TreeNode> stack = new LinkedList<>();
    List<Integer> list = new ArrayList<>();

    // 先按照中右左的顺序遍历
    stack.push(root);
    while (! stack.isEmpty()) {
        TreeNode topNode = stack.pop();
        list.add(topNode.val);

        // 先压入左节点
        if (null != topNode.left) {
            stack.push(topNode.left);
        }
        if (null != topNode.right) {
            stack.push(topNode.right);
        }
    }

    // 倒过来打印集合
    for (int i = list.size() - 1;i >=0 ;i--) {
        System.out.println(list.get(i));
    }
}

4 层次遍历(广度优先)

public void levelOrder(TreeNode root) {
    Queue<TreeNode> queue = new LinkedList<>();

    queue.offer(root);
    while (! queue.isEmpty()) {
        // 队头节点出队
        TreeNode headNode = queue.poll();
        System.out.println(headNode.val);

        // 左右节点不为null也入队
        if (null != headNode.left) {
            queue.offer(headNode.left);
        }
        if (null != headNode.right) {
            queue.offer(headNode.right);
        }
    }
}

⭐其他

* 获取二叉树高度(深度)

public int getDepth(TreeNode root) {
	if (null == root) {
		return 0;
	}
	// 返回左右子树高度较大值加上当前层
	return 1 + Math.max(getDepth(root.left), getDepth(root.right));
}

* 验证二叉搜索树

public boolean validBST(TreeNode root) {
	LinkedList<TreeNode> stack = new LinkedList<>();
	// 记住前一个节点值
	int preVal = Integer.MIN_VALUE;
	
	TreeNode currNode = root;
	while (! stack.isEmpty() || null != currNode) {
	    while (null != currNode) {
	        stack.push(currNode);
	        currNode = currNode.left;
	    }
	
	    // 弹出栈顶节点
	    TreeNode topNode = stack.pop();
	    // 与上一个节点值比较
	    if (topNode.val < preVal) {
	        // 比上一个值小,说明不是递增,即不是搜索树
	        return false;
	    }
	
	    // 更新前节点值
	    preVal = topNode.val;
	    // 更新当前节点
	    currNode = topNode.right;
	}
	
	return true;
}

* 验证平衡二叉树

public boolean validBalance(TreeNode root) {
    // 如果高度不为-1,说明平衡
    return getDepth(root) != -1;
}

// 修改求树高的方法
private int getDepth(TreeNode root) {
    if (null == root) {
        return 0;
    }

    // 先算出左子树的高度
    int lDepth = getDepth(root.left);

    if (lDepth == -1) {
        // 左子树高度为-1,说明左子树已经不平衡,则直接返回-1
        return -1;
    }

    // 再算出右子树高度
    int rDepth = getDepth(root.right);
    if (rDepth == -1 || Math.abs(lDepth - rDepth) > 1) {
        // 右子树高度为-1,或者左右子树高度差大于1,则不平衡
        return -1;
    }
    // 左右子树已平衡,则返回高度
    return 1 + Math.max(lDepth, rDepth);
}

* 二叉搜索树转成有序双向链表

图片来源于网络

PS:图片来源于网络

public static TreeNode getRes(TreeNode root) {
     LinkedList<TreeNode> stack = new LinkedList<>();
     TreeNode currNode = root, pre = null, head = root;
		
	 // 先找到最左节点,作为链表起始节点
     while (null != currNode) {
         stack.push(currNode);
         head = currNode;
         currNode = currNode.left;
     }
	
	 // 中序遍历
     while (! stack.isEmpty() || null != currNode) {
         while (null != currNode) {
             stack.push(currNode);
             currNode = currNode.left;
         }

         TreeNode node = stack.pop();
         // 根据前面的节点进行链接,原地修改,空间复杂度O(1)
         // 也可以先用一个集合记住中序遍历后的节点序列,然后再进行链接,空间复杂度O(n)
         if (null != pre) {
             node.left = pre;
             pre.right = node;
         }
		
		 // 记住前缀节点
         pre = node;
         currNode = node.right;
     }

	 // 返回最左子节点,也就是链表头节点,不能返回root
     return head;
 }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值