我的思路是这样,中序遍历二叉树,然后用一个ArrayList类保存遍历的结果,这样在ArratList中节点就按顺序保存了,然后再来修改指针,虽然没有一点技术含量,但是最后竟然还通过了 哈哈哈。。。
public TreeNode Convert(TreeNode pRootOfTree) { if(pRootOfTree == null){ return null; } ArrayList<TreeNode> list = new ArrayList<>(); Convert(pRootOfTree, list); return Convert(list); } //中序遍历,在list中按遍历顺序保存 public void Convert(TreeNode pRootOfTree, ArrayList<TreeNode> list){ if(pRootOfTree.left != null){ Convert(pRootOfTree.left, list); } list.add(pRootOfTree); if(pRootOfTree.right != null){ Convert(pRootOfTree.right, list); } } //遍历list,修改指针 public TreeNode Convert(ArrayList<TreeNode> list){ for(int i = 0; i < list.size() - 1; i++){ list.get(i).right = list.get(i + 1); list.get(i + 1).left = list.get(i); } return list.get(0); }