题解 | #二叉搜索树与双向链表#

二叉搜索树与双向链表

https://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5

import java.util.*;
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

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

    }

}
*/
public class Solution {
    public TreeNode Convert(TreeNode pRootOfTree) {//栈+队列
        Stack<TreeNode> t=new Stack<>();
        Queue<TreeNode> q=new LinkedList<>();
        TreeNode root=pRootOfTree;
        TreeNode temp;
        t.add(pRootOfTree);

        if(pRootOfTree==null)
            return pRootOfTree;
        while(!t.isEmpty()){//先序遍历存入队列

            if(pRootOfTree.left!=null){
                temp=pRootOfTree;
                pRootOfTree=pRootOfTree.left;
                temp.left=null;
                t.push(temp);
              }else{
            
                q.add(pRootOfTree);
                if(pRootOfTree.right!=null){
                    t.push(pRootOfTree.right);
                }
                pRootOfTree=t.pop();
                 
            }
        }
        
        pRootOfTree=q.poll();
        root=pRootOfTree;
        while(!q.isEmpty()){//挨个连串
            temp=q.poll();
            pRootOfTree.right=temp;
            temp.left=pRootOfTree;
            pRootOfTree=temp;
        }

        return root;
    }
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务