前言
新的一年,好好学习。
正文
问题来源
本问题来自leetcode上的226题。
问题描述
翻转一棵二叉树。
示例 1:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
分析:
递归
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func invertTree(root *TreeNode) *TreeNode {
if nil == root {
return nil
}
root.Left, root.Right = root.Right, root.Left
invertTree(root.Left)
invertTree(root.Right)
return root
}
非递归
/**
* 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 == NULL) return NULL;
queue<TreeNode*> q;
q.push(root); // 根节点入队 操作开始
while(!queue.empty()) // 队列中有元素的时候 重复以下操作
{
TreeNode* cur = q.front();
q.pop();
swap(cur->left,cur->right); // 交换双亲节点的左右孩子
if(cur->left != NULL) q.push(cur->left); // 交换后的左孩子入队
if(cur->right != NULL) q.push(cur->right); // 交换后的右孩子入队
}
return root;
}
};
总结:
勤思考。
结语
不管怎么样好好加油。