题解 | #牛群的树形结构展开II#

牛群的树形结构展开II

https://www.nowcoder.com/practice/3e89ca58f76d4e6aa44cf29569017410

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 {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     中序- 左根右,按照中序遍历,新建节点展开,返回新建节点的头节点
     *
     * @param root TreeNode类
     * @return TreeNode类
     */
    public TreeNode flattenII (TreeNode root) {
        TreeNode res = new TreeNode(-1);
        TreeNode index = res;
        Stack<TreeNode> stack = new Stack<>();
        while (!stack.isEmpty() || root != null) {
            if (root != null) {
                stack.push(root);
                root = root.left;
            } else {
                TreeNode temp = stack.pop();
                index.right = new TreeNode(temp.val);
                index = index.right;
                root = temp.right;
            }
        }
        return res.right;
    }
}

全部评论

相关推荐

头像
04-09 14:29
Java
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务