继续二叉树
Posted ACG哒萌萌沁雪
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了继续二叉树相关的知识,希望对你有一定的参考价值。
“那你又想像杀人魔索要什么?忏悔吗?道歉吗?你所了解的那时的我们已经不存在了!要是哭喊能解气,那你就尽情地哭喊吧!” --------Raina Brown
二叉树反转
针对二叉树的问题,解题之前一定要想清楚究竟是前中后序遍历,还是层序遍历。
翻转一棵二叉树(226)。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool rootisroot(struct TreeNode* root){
if (root ->left != NULL || root ->right != NULL)
{
return true;
}
return false;
};
struct TreeNode* invertTree(struct TreeNode* root){
struct TreeNode * temp = NULL;
if (root == NULL)
{
return root;
}
else if (rootisroot) //其实不需要判断是否为叶子
{
temp = root->left;
root -> left = root -> right;
root->right = temp;
invertTree(root->left);
invertTree(root->right);
}
return root; //这一步return比较重要,因为最后要返回第一层的根节点
}
以上写法为前序遍历,除了中序遍历,其他遍历方法都可以用。
二叉树对称
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3]
则不是镜像对称的:
1
/ \
2 2
\ \
3 3
里外结合,双线操作。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
bool compare(struct TreeNode * left, struct TreeNode * right){
bool outside;
bool inside;
if (left == NULL && right == NULL)
return true;
else if(left == NULL && right != NULL)
return false;
else if (left != NULL && right == NULL)
return false;
else if (left-> val != right -> val)
return false;
outside = compare(left->left, right->right);
inside = compare(left->right, right->left);
return outside && inside;
};
bool isSymmetric(struct TreeNode* root){
if (root == NULL)
return true;
else
{
return compare(root->left, root->right);
}
}
关键是传参的地方,之前遍历的递归都是传入一个参数,这里传两个所以有点难理解,相当于并行处理。
迭代法python版本:
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
else:
Q = queue(50,root)
Q.enqueue(root.left)
Q.enqueue(root.right)
while (Q.isEmpty() == False):
temp_1 = Q.dequeue()
temp_2 = Q.dequeue()
if temp_1 == None and temp_2 == None:
continue #用continue而不是pass
elif temp_1 != None and temp_2 == None:
return False
elif temp_1 == None and temp_2 != None:
return False
elif temp_1.val != temp_2.val:
return False
Q.enqueue(temp_1.left)
Q.enqueue(temp_2.right)
Q.enqueue(temp_1.right)
Q.enqueue(temp_2.left)
return True
入队的操作和之前层序遍历也不同,一次入队四个节点,每次出队两个,然后比较这两个,所以顺序上是先比较外再比较内。无论递归还是队列,初始情况都是从开头的两个节点开始搞。
以上是关于继续二叉树的主要内容,如果未能解决你的问题,请参考以下文章