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

二叉搜索树与双向链表

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) {
        if(pRootOfTree==null) return null;
        TreeNode virHead = new TreeNode(-1);
        Stack<TreeNode> stack = new Stack<>();
        TreeNode pre = virHead ;
        TreeNode cur = pRootOfTree;
        // stack.push(pRootOfTree);
        //中序遍历改变一下就ok
        while(cur!=null||!stack.isEmpty()){
            while(cur!=null){
                stack.push(cur);
                cur =cur.left;
            }
            cur = stack.pop();
             //只修改这部分
            cur.left = pre;
            pre.right = cur;
            pre =cur;

            cur = cur.right;

        }
        //断开虚拟头结点,不然从右往左扫通不过
        TreeNode res = virHead.right;
        virHead.right =null;
        res.left =null;
        return res;
    }
}

全部评论

相关推荐

ResourceUtilization:我嘞个董事长
点赞 评论 收藏
分享
迷茫的大四🐶:自信一点,我认为你可以拿到50k,低于50k完全配不上你的能力,兄弟,不要被他们骗了,你可以的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务