解题思路:利用中序遍历的方式,依次交换所遍历节点的左右子树。
Java 代码实现:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null) return root;
Stack stack=new Stack();
TreeNode p=new TreeNode(0);
stack.push(root);
p=root;
while(p.left!=null){
p=p.left;
stack.push(p);
}
while(!stack.isEmpty()){
TreeNode q=(TreeNode)stack.pop();
TreeNode temp=new TreeNode(0);;
temp=q.left;
q.left=q.right;
q.right=temp;
while(q.left!=null){
stack.push(q.left);
q=q.left;
}
}
return root;
}
}
原题题目:
https://leetcode.com/problems/invert-binary-tree/
版权声明:本文为博主原创文章,未经博主允许不得转载。