二叉树结构如下:
TreeNode{ TreeNode left,right; //左右子树 DataType data; //数据 }
// TreeNode root = ... // if(root == null) return ... Stack<TreeNode> stack = new Stack<>(); stack.push(root); while(!stack.isEmpty()){ TreeNode tn = stack.pop(); TreeNode tmp = tn.left; tn.left = tn.right; tn.right= tmp if(tn.left != null) stack.push(tn.left); if(tn.right != null) stack.push(tn.right); } // ...
public static void reverseTreeNode2(TreeNode root) { if (root==null) { return ; } Queue<TreeNode> queue =new ArrayDeque<TreeNode>(); queue.offer(root); while (!queue.isEmpty()) { TreeNode node=queue.peek(); TreeNode temp=node.left; node.left=node.right; node.right=temp; queue.poll(); if (node.left!=null) { queue.offer(node.left); } if (node.right!=null) { queue.offer(node.right); } } }
//递归版本 TreeNode* invert_BinaryTree_Recursive(TreeNode* head){ if(head==NULL) return NULL; TreeNode* node= invert_Binary_Recursive(head->left); head->left=invert_Binary_Recursive(head->right); head->right=node; return head; } //非递归版本 TreeNode* invert_BinaryTree_NonRecursive(TreeNode* head){ if(head==NULL) return head; stack<TreeNode*> nodes; nodes.push(head); while(!nodes.empty()){ TreeNode* p=nodes.top(); nodes.pop(); swap(p->left,p->right); if(p->left) nodes.push(p->left); if(p->right) nodes.push(p->right); } return head; }
void NonRecursive_Exchange(TreeNode* T) { Stack s; TreeNode* p; if(NULL==T) return; InitStack(&s); Push(&s,T); while(!isEmpty(&s)) { T = Pop(&s); p = T->left; T->left = T->right; T->right = p; if(T->right) Push(&s,T->right); if(T->left ) Push(&s,T->left ); } DestroyStack(&s); }
public class MirrorTreeWithoutRecurrence { private Stack<TreeNode> stack = new Stack<TreeNode>(); private void reverse(TreeNode ele) { if(ele!=null){ TreeNode l = ele.left; ele.left = ele.right; ele.right = l; } } public void mirror(TreeNode root) { TreeNode tmp = root; while(!stack.isEmpty() || tmp!=null){ while (tmp != null) { stack.push(tmp); tmp = tmp.left; } TreeNode t = stack.pop(); tmp = t.right; reverse(t); } } }
class TreeNode():
TreeNode* Mirror(TreeNode *pRoot) {
queue<TreeNode*> tree_queue;
if (pRoot == NULL) return root;
tree_queue.push(pRoot);
while(tree_queue.size() > 0){
TreeNode * pNode = tree_queue.front();
tree_queue.pop();
TreeNode *tmp = pNode->left;
pNode->left = pNode->right;
pNode->right = tmp;
if (pNode->left) tree_queue.push(pNode->left);
if (pNode->right) tree_queue.push(pNode->right);
}
return pRoot;
}
/** * 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) { stack<TreeNode*> s; if(!root)return nullptr; s.push(root); TreeNode* tmp; TreeNode* tn; while(!s.empty()) { tmp = s.top(); s.pop(); tn = tmp->left; tmp->left = tmp->right; tmp->right = tn; if(tmp->right)s.push(tmp->right); if(tmp->left)s.push(tmp->left); } return root; } };