二叉树

1.用一个函数判断一个二叉树是否为平衡二叉树

平衡二叉树的定义为:

它是一棵空树或者它的左右两棵子树的高度差的绝对值不超过1,并且左右两棵子树都是一颗平衡二叉树。

思路:只需要求出离根节点最近或者最远的叶子节点,然后它们到根节点的距离之差是否大于1?

//求最大高度
int maxDepth(TreeNode root){
if(root==null){
return  0;
}
return 1+Math.max(root.left),minDepth(root.right));
}
//求最小高度
int minDepth(TreeNode root){
if(root==null){
return 0;
}
return 1+Math.min(root.left),minDepth(root.right));
}
public static boolean isBalanced(TreeNode root){
return (maxDepth(root)-minDepth(root)<=1);
}

1求二叉树的深度

//二叉树的深度
int TreeDepth(BinaryTreeNode*pRoot)
{
	if (pRoot == NULL)
		return;
	int nLeft = TreeDepth(pRoot->m_pLeft);
	int nRight = TreeDepth(pRoot->m_pRight);
	return (nLeft>nRight) ? (nLeft + 1) : (nRight + 1);
}

非递归版本:

 

//非递归二叉树深度
int maxDepth(TreeNode*root)
if (root == NULL)
return 0;
queue<TreeNode*>q;
q.push(root);
int cur = 1;
int node = 0;
int level = 0;
while (!q.empty())
{
	while (cur)
	{
		TreeNode*tmp = q.front();
		cur--;
		q.pop();
		if (tmp->left)
		{
			node++;
			q.push(tmp->left);
		}
		if (tmp->right)
		{
			node++;
			q.push(tmp->right);;
		}
	}
	level++;
	cur = node;
	node = 0;
}
return level; 
}

二叉树叶子节点到根节点的最小距离:

//二叉树的叶子节点到根节点的最小距离:
	int minDepth(BinaryTreeNode*root)
	{
		if (root == NULL)
			return 0;
		int left = minDepth(root->left);
		int right = minDepth(root->right);
		if (left == 0 && right == 0)
			return 1;
		else if (left == 0)
			return right + 1;
		else if (right == 0)
			return left + 1;
		else
			return min(left, right) + 1;
	}

判断一颗二叉树是否为平衡二叉树:

//判断一棵二叉树是否为平衡二叉树
	bool Isbalanced(BinaryTreeNode*root)
	{
		if (root == null)
			return true;
		int left = TreeDepth(root->left);
		int right = TreeDepth(root->right);
		int diff = left - right;
		if (diff > 1 || diff < -1)
			return false;
		return Isbalanced(root->left) && Isbalanced(root->right);
	}
//用后续遍历方法遍历二叉树的每一个节点,在遍历到一个节点之前,我们就遍历了它的左右子树。只要
//在遍历每个节点的时候记录它的深度(某一个节点的深度等于它到叶节点的长度),就可以一边遍历一边判断
//每个节点是否是平衡的
	bool  Isbalanced(BinaryTreeNode*root,int*pDepth)
	{
		if (root == NULL)
		{
			*pDepth = 0;
			return true;
		}
		int left, right;
		if (isBalanced(root->left, &left) && IsBalanced(root->right, &right)
		{
			int diff = left - right;
			if (diff <= 1 && diff >= -1)
			{
				*pDepth = 1 + (left > right ? left : right);
				return true;
			}

普通二叉树转换成为双向链表:

方法一:非递归版
解题思路:
1.核心是中序遍历的非递归算法。
2.修改当前遍历节点与前一遍历节点的指针指向。
    import java.util.Stack;
    public TreeNode ConvertBSTToBiList(TreeNode root) {
        if(root==null)
            return null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = root;
        TreeNode pre = null;// 用于保存中序遍历序列的上一节点
        boolean isFirst = true;
        while(p!=null||!stack.isEmpty()){
            while(p!=null){
                stack.push(p);
                p = p.left;
            }
            p = stack.pop();
            if(isFirst){
                root = p;// 将中序遍历序列中的第一个节点记为root
                pre = root;
                isFirst = false;
            }else{
                pre.right = p;
                p.left = pre;
                pre = p;
            }      
            p = p.right;
        }
        return root;
    }
方法二:递归版
解题思路:
1.将左子树构造成双链表,并返回链表头节点。
2.定位至左子树双链表最后一个节点。
3.如果左子树链表不为空的话,将当前root追加到左子树链表。
4.将右子树构造成双链表,并返回链表头节点。
5.如果右子树链表不为空的话,将该链表追加到root节点之后。
6.根据左子树链表是否为空确定返回的节点。
    public TreeNode Convert(TreeNode root) {
        if(root==null)
            return null;
        if(root.left==null&&root.right==null)
            return root;
        // 1.将左子树构造成双链表,并返回链表头节点
        TreeNode left = Convert(root.left);
        TreeNode p = left;
        // 2.定位至左子树双链表最后一个节点
        while(p!=null&&p.right!=null){
            p = p.right;
        }
        // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
        if(left!=null){
            p.right = root;
            root.left = p;
        }
        // 4.将右子树构造成双链表,并返回链表头节点
        TreeNode right = Convert(root.right);
        // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
        if(right!=null){
            right.left = root;
            root.right = right;
        }
        return left!=null?left:root;       
    }
方法三:改进递归版
解题思路:
思路与方法二中的递归版一致,仅对第2点中的定位作了修改,新增一个全局变量记录左子树的最后一个节点。
    // 记录子树链表的最后一个节点,终结点只可能为只含左子树的非叶节点与叶节点
    protected TreeNode leftLast = null;
    public TreeNode Convert(TreeNode root) {
        if(root==null)
            return null;
        if(root.left==null&&root.right==null){
            leftLast = root;// 最后的一个节点可能为最右侧的叶节点
            return root;
        }
        // 1.将左子树构造成双链表,并返回链表头节点
        TreeNode left = Convert(root.left);
        // 3.如果左子树链表不为空的话,将当前root追加到左子树链表
        if(left!=null){
            leftLast.right = root;
            root.left = leftLast;
        }
        leftLast = root;// 当根节点只含左子树时,则该根节点为最后一个节点
        // 4.将右子树构造成双链表,并返回链表头节点
        TreeNode right = Convert(root.right);
        // 5.如果右子树链表不为空的话,将该链表追加到root节点之后
        if(right!=null){
            right.left = root;
            root.right = right;
        }
        return left!=null?left:root;       
    }
//普通二叉树的创建和排序二叉树的创建
				void createTree(TreeNode *&root)
				{
					int i;
					cin >> i;
					if (i == 0)
						return;
					TreeNode*tmp = new TreeNode(val);
					if (root == NULL)
					{
						root = tmp;
						createTree(root->left);
						createTree(root->right);

					}
				}
				void Insert(TreeNode*&root, int val)
				{
					TreeNode*tmp = new TreeNode(val);
					if (root == NULL)
						root = tmp;
					else if (val < root->val)
						Insert(root->left, val);
					else if (val>root->val)
						Insert(root->right, val);
					else return;
				}
				//二叉排序树
				void createSort(TreeNode*&root)
				{
					int arr[10] = { 8, 3, 5, 1, 9, 2, 6, 7, 14 }
						for (auto a : arr)
							Insert(root, a);
				}
				//二叉树的遍历
				void recursivePreorder(TreeNode*root)
				{
					if (root)
					{
						cout << root->val << ' ';
						recursivePreorder(root->left);
						recursivePreorder(root->right);
					}
				}
				void recursiveInorder(TreeNode*root)
				{
					if (root)
					{
						recursiveInorder(TreeNode->left);
						recursiveInorder(TreeNode->right);
					}
				}
				void recursivePostorder(TreeNode*root)
				{
					if (root)
						recursivePostorder(root->left);
					recursivePostorder(root->right);
				}
			}


 


//二叉树叶子节点的数量
			//叶子节点的个数
			int leafCounts(TreeNdoe *root)
			{
				if (root == NULL)
					return 0;
				if (root->left == NULL&&root->right == NULL)
				{
					return 1;
					return leafCounts(root->left) + leafCounts(root->right);
				}
			}

直接求所有节点总数:

//节点总数

//判断是否为二叉树的子结构

//判断是否为二叉树的子结构
            bool isSub(TreeNode*root, TreeNode*sroot);
            {
                if (sroot == NULL)
                    return true;
                if (root == NULL)
                    return false;
                if (root->val != sroot->val)
                    return false;
                return isSub(root->left, sroot->left) && isSub(root->right, sroot->right);
            }
//二叉树的子结构
            bool isSubstruct(TreeNode*root, TreeNode*sroot)
            {
                if (root == NULL || sroot == NULL)
                    return false;
                bool result = false;
                if (root->val == sroot->val)
                    result = isSub(root, sroot);
                if (!result)
                    result = isSubstruct(root, sroot);
                if (!result)
                    result = isSubstruct(root->left, sroot);
                return result;
            }

判断是否为镜像二叉树

//镜像二叉树
				bool isMirror(TreeNode *rootA, TreeNode *rootB){
					if (rootA == NULL&&rootB == NULL)
						return false;
				if (rootA == NULL || rootB == NULL)
					return false;
				if (rootA->val != rootB->val)
					return false;
				return isMirror(rootA->left, rootB->right) && isMirror(rootA->right,rootB->left)
}

判断是否为完全二叉树

//判断是否为完全二叉树
			bool isCompleteTree(TreeNode*root)
			{
				if (root == NULL)
					return true;
				int tag = 0;
				queue<TreeNode*>q;
				q.push(root);
				while (!q.empty())
				{
					TreeNode*tmp = q.front();
					q.pop();
					if (tmp->left&&tag)
					{
						q.push(tmp->left);
					else if (!tmp->left&&tag)
						return false;
					else if (!tmp = tmp->left)
						tag = 1;
					if (tap->right&&!tag)
						q.push(tmp->right);
					else if (tmp->right&&tag)
						return false;
					else if (!tmp->right)
						tag = 1;
					}
					return true;
				}

重建二叉树

	//重建二叉树
				TreeNode*rebulidTree(int *pre, int *in, int len)
				{
					if (pre == NULL || in = NULL || len <= 0)
						return NULL;
					int val = post[len - 1];
					int i = 0, j;
					while (i < len - 1 && in[i] != val)
					{	i++;
					if (i == len)
						return NULL;
					root->left = rebulidTree(pre + 1, in, i);
					root->right = rebulidTree(pre + 1, in + i + 1, len - i - 1)
						return root;
				}

				}
	//二叉树路径为给定值的所有路径
				void findPath(TreeNode*root, vecctor<vector<int>>&path, int target)
				{
					if (root == NULL)
						return;
					path.push_back(root->val);
					if (root->left == NULL&&root->right == NULL&&target == root->val)
					{
						res.push_back(path);
						return;
					}

				}
				if (root->left)
				{
					findPath(root->left, res, path, target - root->val);
				}
				if (root->right)
				{
					findPath(root->right, res, path, target - root->val);
				}
				path.pop_back();
			}
			vector<vector<int>>res;
			{
				vector<vector<int>>res;
				vector<int>path;
				findparent(root, res, path, target);
				return res;
			}
//二叉树最低公共父节点
			bool father(TreeNode*n1, TreeNode*n2)
			{
				if (n1 == NULL)
					return false;
				if (n1 == n2)
					return true;
				return father(n1->left, n2) || father(n1->right, n2);
			}
	       //二叉树的最低公共祖先
			TreeNode*findParent(TreeNode*root, TreeNode*n1, TreeNode*n2, TreeNode&parent)
			{
				if (root == NULL)
					if (father(root, n1) && father(root, n2))
					{
						parent = root;
						findParent(root->left, n1, n2, parent);
						findParent(root->right, n1, n2, parent);

					}
				return parent;
			}
//判断一颗二叉树是否为搜索二叉树
			int isBST2(struct node*node)
			{
				return(isBSTUtil(node, int INT_MIN, INT_MAX))
			}
			int isBSTUtil(struct node*node, int min, int max)
			{
				if (node == NULL)
					return (true);
				if (node->data <= min || node->data >= max)
					return false;
				return;
				isBSTUtil(node->left, min, node->data) && isBSTUtil(node->right, node->data, max)
			};
		}

//求二叉树的第K层节点个数

/*二叉树的第K层节点个数
		递归解法:
			(1)如果二叉树为空或者K<1返回0
			(2)如果二叉树不为空且K==1,返回1
			(3)如果二叉树不为空且K>1,返回左子树中K-1层的节点个数与右子树中K-1层节点个数之和*/
		int getNode(TreeNode*root, int 1)
		{
			if (root == NULL || K < 1)
				return 0;
			if (K == 1)
				return 1;
			int leftNUM = getNode(root->left, K - 1)
				int rightNUM = getNode(root->right, K - 1);
			return leftNUM + rightNUM;
		}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值