Leetcode17.12 BiNode 中序遍历

  需要注意边界条件以及 环 的处理。

  JAVA 中序遍历:

public final TreeNode convertBiNode(TreeNode root) {
        return dfs2(root);
    }

    public final TreeNode dfs2(TreeNode node) {
        if (node == null) return node;
        TreeNode preRight = node.right;
        //构建左子树
        TreeNode root = dfs2(node.left);
        if (root == null) root = node;
        else {
            //左子树连接 node
            TreeNode leaf = root;
            while (leaf.right != null) leaf = leaf.right;
            leaf.right = node;
            node.left = null;
        }
        if (preRight != null) {
            //构建右子树
            TreeNode rightRoot = dfs2(preRight);
            // node 连接右子树
            node.right = rightRoot;
        }
        return root;
    }

  JS 中序遍历:

/**
 * Definition for a binary tree node.
 * function TreeNode(val) {
 *     this.val = val;
 *     this.left = this.right = null;
 * }
 */
/**
 * @param {TreeNode} root
 * @return {TreeNode}
 */
var convertBiNode = function (root) {
    return dfs(root);
};

var dfs = function (node) {
    if (!node) return node;
    let leftRoot = dfs(node.left);
    if (!leftRoot) leftRoot = node;
    else {
        let leaf = leftRoot;
        while (leaf.right) leaf = leaf.right;
        leaf.right = node;
        node.left = null;
    }
    let rightRoot = dfs(node.right);
    node.right = rightRoot;
    return leftRoot;
}

 

posted @ 2020-11-01 23:13  牛有肉  阅读(88)  评论(0编辑  收藏  举报