本篇blog主要使用递归方式解决Tree的DFS问题,至于非递归方式,需要使用堆栈的方式。具体的原理可以参考《算法导论》。
对于Tree的深度搜索问题的解题模式:
1)首先判断是否能够用深度搜索策略(DFS)解决问题。DFS能够解决的问题的一般特点是:如果把左右子树作为独立的Tree来看,使用同样的算法同样可以解决;
2)确认DFS可以解决问题后,一般使用递归的方式解决问题。确定递归的退出条件和处理是关键,也就是边界的处理:(1)叶结点是边界(2)Tree的倒数第二层是边界,等等;
3)运用递归的方式处理左子树和右子树;
4)root,左子树和右子树都处理后,集中三者的处理结果得出问题的最终解;
1. Maximum Depth of Binary Tree(104)
描述:Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node
int maxDepth(struct TreeNode* root) {
int depth = 0;
int leftDepth;
int rightDepth;
//如果空树,深度为0
if(root == NULL)
{
return depth;
}
// 递归求解左儿子和右儿子的深度
leftDepth = maxDepth(root->left);
rightDepth = maxDepth(root->right);
// 在左儿子和右儿子之间选取较大的深度加上1就是整个树的深度
if(leftDepth > rightDepth)
{
depth = leftDepth + 1;
}
else
{
depth = rightDepth + 1;
}
return depth;
}
2. Invert Binary Tree(226)
描述:Invert a binary tree.
4
/ \
2 7
/ \ / \
1 3 6 9
to
4
/ \
7 2
/ \ / \
9 6 3 1
struct TreeNode* invertTree(struct TreeNode* root)
{
struct TreeNode *p;
//树空则返回
if(root == NULL)
{
return root;
}
// 交换root的左儿子和右儿子
p = root->left;
root->left = root->right;
root->right = p;
// 递归invert root的左儿子
invertTree(root->left);
// 递归invert root的右儿子
invertTree(root->right);
return root;
}
3. Same Tree (100)
描述:Given two binary trees, write a function to check if they are equal or not.Two binary trees are considered equal if they are structurally identical and the nodes have the same value
bool isSameTree(struct TreeNode* p, struct TreeNode* q)
{
bool a = false;
bool b = false;
bool c = false;
// 两树都空,则相同
if(p == NULL && q == NULL)
{
return true;
}
//任意一棵树空,另一颗不空,则不同
if(p == NULL && q != NULL)
{
return false;
}
if(p != NULL && q == NULL)
{
return false;
}
//value不同则不同
if(p->val != q->val)
{
return false;
}
a = true;
// 递归check p和q的左儿子是否相同
b = isSameTree(p->left,q->left);
// 递归check p和q的右儿子是否相同
c = isSameTree(p->right,q->right);
// 只有p和q相同,对应的左儿子和右儿子都相同,两树才相同
if(a == true && b == true && c == true)
{
return true;
}else
{
return false;
}
}
4. Balanced Binary Tree (110)
描述:Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.
bool isBalanced(struct TreeNode* root) {
int leftHeight;
int rightHeight;