Max Tree

Description

Given an integer array with no duplicates. A max tree building on this array is defined as follow:

  • The root is the maximum number in the array
  • The left subtree and right subtree are the max trees of the subarray divided by the root number.

Construct the max tree by the given array.

思路:利用数组实现基本数据结构的调整,当前遍历到的数字比stack中的最后一个大时,将stk中的最后一个数字转变为当前节点的左子树,循环调整至stack为空或者stack中的最后节点值大于新节点的值。如果stack不为空,说明stack中的最后一个节点值大于新节点值,则将新节点设为stack中的最后一个节点的右子树,将新节点存入stack。

public class Solution {
  /**
   * @param A
   *            : Given an integer array with no duplicates.
   * @return: The root of max tree.
   */
  public static TreeNode maxTree(int[] A) {
    // write your code here
    Stack<TreeNode> stack = new Stack<TreeNode>();     //申请栈存放节点		
    TreeNode root = null;                            
    for (int i = 0; i <= A.length; i++) {
      TreeNode right = i == A.length ? new TreeNode(Integer.MAX_VALUE) //如果i==length,新建节点设置值为无穷大,否则值为A[i]
          : new TreeNode(A[i]);
      while (!stack.isEmpty()) {        //如果栈不为空
        if (right.val > stack.peek().val) {			//如果新建节点的值比栈顶大
          TreeNode nodeNow = stack.pop();          //临时保存栈顶节点并弹出
          if (stack.isEmpty()) {                   //如果栈为空
            right.left = nodeNow;                  //临时保存的栈顶的节点是当前新建节点的左子树
          } else {
            TreeNode left = stack.peek();
            if (left.val > right.val) {            
              right.left = nodeNow;                //新建节点的左子树为临时保存节点
            } else {
              left.right = nodeNow;                //当前栈顶的节点的右子树为新建节点
            }
          }
        } else
          break;
      }
      stack.push(right);                          //将新建节点压入栈中
    }
    return stack.peek().left;
  }
}

  

猜你喜欢

转载自www.cnblogs.com/FLAGyuri/p/12077173.html
max