invertbinarytree

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26

* @Title: invertBinaryTree2
* @Description: 翻转二叉树的非递归解法,用栈来模拟
* @param root
* @return void
* @throws
*/
public static void (TreeNode root) {
if (root == null) {
return;
}
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
TreeNode current = stack.pop();
TreeNode temp = current.left;
current.left = current.right;
current.right = temp;
if(current.left != null){
stack.push(current.left);
}
if(current.right != null){
stack.push(current.right);
}
}
}