翻转一棵二叉树。
示例:
输入:
4
/ \
2 7
/ \ / \
1 3 6 9
输出:
4
/ \
7 2
/ \ / \
9 6 3 1
我刚开始的想法,直接递归进行值的替换,结果竟然显示不对,一直没想明白为啥不对
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root !=null){
changeNode(root.left,root.right);
}
return root;
}
public void changeNode(TreeNode left,TreeNode right){
if(left==null){
left =right;
}else if(right ==null){
right=left;
}else{
int temp = right.val;
right.val = left.val;
left.val = temp;
changeNode(left.right,right.left);
changeNode(left.left,right.right);
}
}
}
于是采用了如下方法
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null||root.left==null&&root.right==null){
return root;
}
TreeNode left = root.left;
TreeNode right = root.right;
root.right= invertTree(left);
root.left= invertTree(right);
return root;
}
}
转载:https://blog.csdn.net/u012124438/article/details/102593088
查看评论