Binary Tree & Binary Search Tree

本文详细介绍了二叉树的基本知识点,包括前序、中序和后序遍历,以及平衡二叉树、完全二叉树和二叉搜索树的概念。还讨论了如何获取二叉树的最大和最小高度,判断是否为平衡或对称二叉树,以及如何确定两个二叉树结构相同。此外,针对二叉搜索树,文章解释了如何判断其合法性以及在给定范围内打印BST键的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Binary Tree

Definition: at most two children node.
Binary Tree Example:

class TreeNode {
	int value;
	TreeNode* left;
	TreeNode* right;
}
基本知识点
Tree Traverse
  1. Pre-order
    先打印自己的节点,然后打印左节点(recurse后变成当前节点),然后再右节点。
    10 5 2 7 15 12 20
    在这里插入图片描述
void preOrder(TreeNode* root) {
	if (root == NULL) {
		return;// base case
		// 真正的basecase是叶节点下的空指针,而不是叶节点
	}
	cout << root->value << endl;
	preOrder(root->left);
	preOrder(root->right);
}
  1. In-order
    永远把current node放在中间,只有在把左子树的打印完之后,才打印current
    2 5 7 10 12 15 20
    在这里插入图片描述
void inOrder(TreeNode* root) {
	if (root == NULL) {
		return;
	}
	inOrder(root->left);
	cout << root->value << endl;
	inOrder(root->right);
}
  1. Post-order
    永远把current node放在最后打印,先左,后右,最后current。
    2 7 5 12 20 15 10
    在这里插入图片描述
void postOrder(TreeNode* root){
	if (root == NULL) return;
	postOrder(root->left);
	postOrder(root->right);
	cout << root -> value << endl;
}

Trick: Base case is usually refers to the null ChidNode below the leaf node.

基本概念
  1. Balanced Binary Tree: is common defined as a binary tree in which the depth of the left and right subtrees of every node differ by 1 or less.
    对于任意节点,左子树和右子树的差不超过1,左边的高度和右边的高度大体相当。

  2. Complete Binary Tree : is a binary tree is which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

  3. Binary Search Tree: for every single node in the tree, the values in its left subtree are all smaller than its value, and the values in its right subtree are all larger than its value.
    一般不允许有重复的node

Discussion

在这里插入图片描述
Fundamental Knowledge:

  1. Traverse of a binary tree
    1. Balanced Binary Tree
    2. Complete Binary Tree
    3. Binary Search Tree(BST)
Get (max)Height of a Binary Tree
public int getHeight(TreeNode root) {
	if (root == null) {
		return 0;
	}
	int left = getHeight(root.left);
	int right = getHeight(root.right);
	return Math.max(left, right) + 1;
}

Time = O(n)
Space = O(height)

Get (min)Height of a Binary Tree

Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.
Note: A leaf is a node with no children.

class Solution {
    public int minDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = minDepth(root.left);
        int right = minDepth(root.right);
        return (left == 0 || right == 0) ? left+right+1 : Math.min(left, right) + 1;
    }
}
How to determine whether a binary tree is a balanced binary tree?

(This is not an optimal solution)

public boolean isBalanced(TreeNode root) {
	if (root == null) return true;
	int left = getHeight(root.left);
	int right = getHeight(root.right);
	if (Math.abs(left - right) > 1) return false;
	return isBalanced(root.left) && isBalanced(root.right);
} 

在第一层,假设有n个节点,getHeight(left)(调用一次,每次O(n/2))和getHeight(right)(调用一次)的时间复杂度是o(n)。
在第二层,getHeight(left)(调用两次,每次O(n/4))和getHeight(right)(调用两次)的时间复杂度是o(n)。

一共有log(n)层,每次的时间复杂度为O(n),所以一共是nlog(n)

How to judge whether a binary tree is symmetric?

在这里插入图片描述

boolean isSymmetric(TreeNode one, TreeNode two) {
	// base case 1
	if (one == null && two  == null) return true;
	// base case 2
	else if (one == null || two == null) return false;
	// base case 3
	else if (one.value != two.value) return false;
	return isSymmetric(one.left, two.right) && isSymmetric(one.right, two.left);
}

在这里插入图片描述
Time: O(n)
Space: call stack的层数。O(n) -> O(height). If the tree is balanced, then the height is log(n)

Let’s assume if we tweak lchild with rchild of an arbitrary node in a binary tree, then the structure of the tree are not changed. Then how can we determine whether two binary trees structures are identical.

在这里插入图片描述

public boolean isIdentical(TreeNode one, TreeNode two) {
	// base case 1
	if (one == null && two  == null) return true;
	// base case 2
	else if (one == null || two == null) return false;
	// base case 3
	else if (one.value != two.value) return false;
	// recursive rule
	return (ifIdentical(one.left, two left) && ifIdentical(one.right, two.right)  // case 1
	|| 
	ifIdentical(one.left, two.right) && ifIdentical(one.right, two.left))
}

分析recursion function的时间复杂度:还原recursion tree。
在这里插入图片描述
If the original tree has log2(n) level, then the recursion tree has log2(n) level.
因为:这 个recursion function care的关系,是当前层的下一层,所以recursion tree和original tree的层数一样。
binary tree: 1 2 4 8 16 32…
quadral tree: 1 4 16 64 256…
四叉树时间复杂度:只考虑最后一层的node。
第一层 1个node,第二层42个node, 第三层43个node。。。最后一层4logn个node。
一共log(n)层,所以时间复杂度为:O(4long(n)) = 22logn=2log(n方) = O(n2)
Space: 由recursion的层数决定。如果是balance tree,层数为log(n)

Binary Search Tree

How to determine a binary tree is a BST?
bool isBSTHelper(TreeNode root = 10, int min, int max) {
	if (root == null) return true;
	// recursive rule
	if (root.val > max || root.val < min) return false;
	return isBSTHelper(root.left, min, root.val) && isBSTHelper(root.right, root.val, max);
}
Print BST keys in the given range

Given two values k1 and k2(where k1 < k2) and a root ptr to a Binary Search Tree. Print all the keys of the tree in range k1 to k2. Print all the keys in an increasing order.
Property: For BST, if we print out all element in an in-order sequence, then they satisfy that they are printed in an increasing order.
Solution 1: In-order iterative way

public void printBST(NodeRoot root, int k1, int k2) {
	if (root == null) return;
	printBST(root.left, k1, k2);
	if (root.val > k1 && root.val < k2) {
		print();
	}
	printBST(root.right, k1, k2);
}

Solution 2: Truncate

public void printBST(NodeRoot root, int k1, int k2) {
	if (root == null) return;
	if (root.val > k1) {
		printBST(root.left, k1, k2);
	}
	if (root.val > k1 && root.val < k2) {
		print();
	}
	if (root.val < k2) {
		printBST(root.right, k1, k2);
	}
}

Time: O(n) worst case

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值