【发布时间】:2018-04-21 00:35:28
【问题描述】:
我正在尝试解决“二叉树颠倒”这个问题。例如,如果我们有一棵二叉树:
1
/ \
2 3
/ \
4 5
运行我的函数后,会变成:
4
/ \
5 2
/ \
3 1
我得到了以下递归代码,但无法理解 //1 和 //5 之间的步骤;
public TreeNode UpsideDownBinaryTree(TreeNode root)
{
if (root == null) return null;
TreeNode parent = root, left = root.left, right = root.right;
if (left != null)
{
TreeNode ret = UpsideDownBinaryTree(left); //1
left.left = right; //2
left.right = parent; //3
return ret; //4
}
return root; //5
}
有人可以详细解释一下每个步骤在这里做什么吗?另外,为什么我们有两个单独的返回:return ret、return root?
我知道如何对常规数组、列表和一些二叉树进行递归。但是这个递归逻辑似乎和我之前知道的不一样。我什至用IDE单步执行,但还是不能完全理解。
对于这个问题,我也有以下迭代代码。我可以理解这段代码。它从根扫描树到离开。但是对于递归代码,它是从根到叶扫描树并从叶到根构建新树?我理解正确吗?
public TreeNode UpSideDownTree_Iterative(TreeNode root)
{
TreeNode node = root,parent = null,right = null;
while (node != null) {
TreeNode left = node.left;
node.left = right;
right = node.right;
node.right = parent;
parent = node;
node = left;
}
return parent;
}
【问题讨论】:
-
二叉树中的递归函数解释:stackoverflow.com/questions/7863538/…
标签: recursion binary-tree