leetcode上刷到一道翻转树的问题,我的递归和答案的递归正好是两种思路,在这里总结一下。
- 我的递归,实际上是自顶向下(先操作,再递归)
public TreeNode inverseTree(TreeNode root){
inverse(root);
return root;
}
public void inverse(TreeNode root){
if(root == null || (root.left ==null && root.right ==null)) return;
if(root.left!=null && root.right!=null){
TreeNode temp = root.left;
root.left = root.right;
root.right = temp;
}else if(root.left!=null){
root.right = root.left;
root.left = null;
}else if(root.right!=null){
root.left = root.right;
root.right = null;
}
inverse(root.left);
inverse(root.right);
}
- 答案的递归,实际上自底向上(先递归,再操作)
public TreeNode inverseTree(TreeNode root){
if(root == null) return null;
TreeNode left = inverseTree(root.left);
TreeNode right = inverseTree(root.right);
root.left = right;
root.right = left;
return root;
}