翻转二叉树
2017-04-19 10:56
148 查看
题目:
翻转一棵二叉树
样例
思路:
在遍历的过程中将每个结点的左右子树进行交换。从根节点出发,如果操作的节点是空值,则不进行任何操作,否则交换左右儿子。
具体代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
TreeNode *node;
if(root==NULL) return;
else{
node=root->right;
root->right=root->left;
root->left=node;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
}
};
感悟:
注意要增加一个过渡节点,从而实现节点的交换。
翻转一棵二叉树
样例
1 1 / \ / \ 2 3 => 3 2 / \ 4 4
思路:
在遍历的过程中将每个结点的左右子树进行交换。从根节点出发,如果操作的节点是空值,则不进行任何操作,否则交换左右儿子。
具体代码:
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param root: a TreeNode, the root of the binary tree
* @return: nothing
*/
void invertBinaryTree(TreeNode *root) {
// write your code here
TreeNode *node;
if(root==NULL) return;
else{
node=root->right;
root->right=root->left;
root->left=node;
invertBinaryTree(root->left);
invertBinaryTree(root->right);
}
}
};
感悟:
注意要增加一个过渡节点,从而实现节点的交换。
相关文章推荐
- 翻转一棵二叉树
- leetCode之翻转二叉树
- 翻转二叉树(Invert Binary Tree)
- 翻转二叉树(Invert Binary Tree)
- 翻转二叉树(leetcode-226)
- 翻转二叉树
- LintCode 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- lintcode 容易题:Invert Binary Tree 翻转二叉树
- PAT-A1102. 二叉树-翻转 层序、中序输出
- 翻转二叉树
- 翻转二叉树
- 翻转二叉树
- 二叉树的翻转操作
- 算法题:lintcode#175 翻转二叉树(java)
- Lintcode 175. 翻转二叉树
- LinkCode-翻转二叉树
- 翻转二叉树节点数据
- LeetCode Invert Binary Tree 翻转二叉树