码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 226: Invert Binary Tree(二叉树反转)

时间:2015-06-13 15:44:12      阅读:418      评论:0      收藏:0      [点我收藏+]

标签:leetcode   invert binary tree   二叉树反转   

nvert a binary tree.

     4
   /     2     7
 / \   / 1   3 6   9
to
     4
   /     7     2
 / \   / 9   6 3   1
Trivia:
This problem was inspired by this original tweet by Max Howell:

  Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so fuck off.

非递归算法:

1、交换根节点的左右子节点

2、交换第二层每个节点的左右子节点

....

这个与二叉树层次遍历类似,代码如下:

TreeNode* invertTree2(TreeNode* root) {
		queue<TreeNode*> tree_queue;
		if (root == NULL)
			return root;
		tree_queue.push(root);
		while(tree_queue.size() > 0){
			TreeNode * pNode = tree_queue.front();
			tree_queue.pop();
			TreeNode * pLeft = pNode->left;
			pNode->left = pNode->right;
			pNode->right = pLeft;
			if (pNode->left)
				tree_queue.push(pNode->left);
			if (pNode->right)
				tree_queue.push(pNode->right);
		}
		return root;
	}

递归算法:

1、交换根节点的左右子树。

2、对左右子树分别执行递归反转 。

代码如下:

   TreeNode* invertTree(TreeNode* root) {
	if(root==NULL)
			return NULL;
		TreeNode * ptmpNode = root->left;
		root->left = invertTree(root->right);
		root->right = invertTree(ptmpNode);
		return root;
    }








Leetcode 226: Invert Binary Tree(二叉树反转)

标签:leetcode   invert binary tree   二叉树反转   

原文地址:http://blog.csdn.net/sunao2002002/article/details/46482559

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!