递归,C# codes如下:
class TreeNode
{
public TreeNode LeftSon { get; set; }
public TreeNode RightSon { get; set; }
public string Value { get; set; }
public TreeNode(string value = null, TreeNode leftSon=null, TreeNode rightSon=null)
{
this.LeftSon = leftSon;
this.RightSon = rightSon;
this.Value = value;
}
public static TreeNode Replace(TreeNode rootNode)
{
if (rootNode == null)
{
return rootNode;
}
else if (rootNode.LeftSon == null && rootNode.RightSon == null)
{
return rootNode;
}
else
{
TreeNode reserveNode = rootNode.LeftSon;
rootNode.LeftSon = Replace(rootNode.RightSon);
rootNode.RightSon = Replace(reserveNode);
return rootNode;
}
}
}