LeetCode Invert Binary Tree 反转二叉树

LeetCode Invert Binary Tree  反转二叉树

思路:递归解决,在返回root前保证该点的两个孩子已经互换了。注意可能给一个Null。

C++

 /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* invertTree(TreeNode* root) {
if(!root) return ;//重要在这而已
if(root->left) invertTree(root->left);
if(root->right) invertTree(root->right);
TreeNode* tmp=root->right;
root->right=root->left;
root->left=tmp;
return root;
}
};

AC代码

python3

  递归

 # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root!=None:
root.left, root.right= self.invertTree(root.right), self.invertTree(root.left)
return root

AC代码

  迭代

 # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack=[root]
while stack!=[]:
back=stack.pop()
if back!=None:
back.left, back.right= back.right, back.left
stack.extend([back.left,back.right])#也可以写成stack+=back.left,back.right return root

AC代码

上一篇:易企秀H5 json配置文件解密分析


下一篇:十一、Shell 输入/输出重定向