题目:
反转一个二叉树
4 / \ 2 7 / \ / \ 1 3 6 9to
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; }
* }
*/
public class Solution {
public TreeNode invertTree(TreeNode root) {
if(root==null)
return null;
TreeNode tmpNode=root.left;
root.left=invertTree(root.right);
root.right=invertTree(tmpNode);
return root;
}
}
没什么好说的,这题不难,递归一步步返回的节点都是反转后的,最后返回到根节点自己
这样一棵树就被反转啦!
当时在学数据结构的时候,完全对递归没印象,递归在树结构里还真是好用啊
但是空有想法,写的时候总是出错,最后偷偷瞄了别人的代码,才恍然大悟
本渣 准备深入学习一下递归了!