/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
private TreeNode head=null;
private TreeNode tail=null;
public TreeNode Convert(TreeNode pRootOfTree) {
visit(pRootOfTree);
return head;
}
public void visit(TreeNode root) {
if (root == null) {
return;
}
visit(root.left);
createList(root);
visit(root.right);
}
public void createList(TreeNode cur){
cur.left=tail;//把当前的节点接到链表的尾部
if(tail!=null){//双向连接
tail.right=cur;
}else{
head=cur;
}
tail=cur;//更新尾结点为当前结点,或者说:尾结点后移
}
}
剑指offer 二叉树转为双向链表
最新推荐文章于 2024-08-14 21:25:09 发布