[剑指offer]二叉搜索树与双向链表

在这里插入图片描述
思路:
先用中序遍历树,并存入栈中。如果是第一个节点就记为root,保存两个节点一前一后,将前一个节点的右节点和后一个节点的左节点交换

实现:

/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
//非递归
import java.util.Stack;
public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {
        if(pRootOfTree == null )
            return null;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode p = pRootOfTree;
        TreeNode pre = null;
        boolean isFirst = true;
        while(p != null || !stack.isEmpty()){
            while(p != null){
                stack.push(p);
                p = p.left;
            }
            p = stack.pop();
            if(isFirst){
                pRootOfTree = p;
                pre = pRootOfTree;
                isFirst = false;
            }
            else{
                pre.right = p;
                p.left = pre;
                pre = p;
            }
            p = p.right;
        }
        return pRootOfTree;
    }
//递归
public class Solution {
    TreeNode head = null;
    TreeNode realHead = null;
    public TreeNode Convert(TreeNode pRootOfTree) {
        ConvertSub(pRootOfTree);
        return realHead;
    }
    private void ConvertSub(TreeNode pRootOfTree){
        if(pRootOfTree == null){
            return;
        }
        ConvertSub(pRootOfTree.left);
        if(head == null){
            head = pRootOfTree;
            realHead = head;
        }
        else {
            head.right = pRootOfTree;
            pRootOfTree.left = head ;
            head = pRootOfTree;
        }
        ConvertSub(pRootOfTree.right);
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37344518/article/details/85010456