[leetcode]Invert Binary Tree | 普通一码农
Invert a binary tree.
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.
X. Recursive
http://www.programcreek.com/2014/06/leetcode-invert-binary-tree-java/
It's better to do null or valid check at first.
X. Iterative
http://blog.welkinlan.com/2015/09/18/invert-binary-tree-leetcode-lintcode-java/
Invert a binary tree.
to
- 4
- / \
- 2 7
- / \ / \
- 1 3 6 9
Trivia:
- 4
- / \
- 7 2
- / \ / \
- 9 6 3 1
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.
X. Recursive
- public void invertTreeSingle(TreeNode cur){
- if(cur == null) return;
- TreeNode temp = cur.left;
- cur.left = cur.right;
- cur.right = temp;
- invertTreeSingle(cur.left);
- invertTreeSingle(cur.right);
- }
- public TreeNode invertTree(TreeNode root) {
- invertTreeSingle(root);
- return root;
- }
TreeNode* invertTree(TreeNode* root) {
if
(root == NULL)
return
NULL;
TreeNode *temp = root->left;
root->left = invertTree(root->right);
root->right = invertTree(temp);
return
root;
}
It's better to do null or valid check at first.
public TreeNode invertTree(TreeNode root) { if(root!=null){ helper(root); } return root; } public void helper(TreeNode p){ TreeNode temp = p.left; p.left = p.right; p.right = temp; if(p.left!=null) helper(p.left); if(p.right!=null) helper(p.right); } |
http://blog.welkinlan.com/2015/09/18/invert-binary-tree-leetcode-lintcode-java/
- public TreeNode invertTree(TreeNode root) {
- if(root == null) return root;
- Queue<TreeNode> queue = new LinkedList<TreeNode>();
- queue.offer(root);
- while (!queue.isEmpty()) {
- TreeNode node = queue.poll();
- TreeNode nodeLeft = node.left;
- node.left = node.right;
- node.right = nodeLeft;
- if(node.left != null) queue.offer(node.left);
- if(node.right != null) queue.offer(node.right);
- }
- return root;
- }
public TreeNode invertTree(TreeNode root) {
if (root == null) return root;
Stack<TreeNode> stack = new Stack<TreeNode>();
TreeNode p = root;
TreeNode q = null, r = null;
while (p != null) {
stack.push(p);
p = p.left;
}
while (!stack.isEmpty()) {
p = stack.pop();
q = p.right;
while (q != null) {
stack.push(q);
q = q.left;
}
r = p.right;
p.right = p.left;
p.left = r;
}
return root;
}
Read full article from [leetcode]Invert Binary Tree | 普通一码农