Leetcode226.翻转二叉树
推荐一个好理解的答案:
class Solution {
public TreeNode invertTree(TreeNode root) {
if (root == null) {
return null;
}
/**
* 类似于数组中两个数交换
*/
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
return root;
}
}
官方答案:
class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null){
return null;
}
TreeNode left= invertTree(root.left); //这里容易写错,经常会认为:left翻转后应该赋值给right
TreeNode right= invertTree(root.right);
root.left=right;
root.right=left;
return root;
}
}
完整调试代码:
public TreeNode invertTree(TreeNode root) {
if (root == null) {
System.out.println("return null");
return null;
}
/**
* 类似于数组中两个数交换
*/
TreeNode tmp = root.left;
root.left = invertTree(root.right);
root.right = invertTree(tmp);
System.out.println("return value:" + root.val+"\n");
return root;
}
运行结果:
4
/ \
2 7
/ \ / \
1 3 6 9
return null
return null
return value:9
return null
return null
return value:6
return value:7
return null
return null
return value:3
return null
return null
return value:1
return value:2
return value:4
4
/ \
7 2
/ \ / \
9 6 3 1
Process finished with exit code 0
原文地址:https://blog.csdn.net/zhangjin1120/article/details/140483550
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!