二叉树(三)

来源:互联网 发布:冰川网络能涨多少个板 编辑:程序博客网 时间:2024/05/05 12:18

12. 二叉树两个结点的最低共同父结点

public Node getLCA(Node root, Node A, Node B) {if (root == null) {return null;}if (A == root || B == root) {return root;}Node leftNode = getLCA(root.getLeft(), A, B);Node rightNode = getLCA(root.getRight(), A, B);if (leftNode == null) {return rightNode;}else if (rightNode == null) {return leftNode;}else {return null;}}

13. 把一个有序整数数组放到二叉树中

Node array2Tree(int[] array) {return helper(array, 0, array.length - 1);}Node helper(int[] array, int start, int end) {if (start > end)return null;int m = start + (end - start) / 2;Node root = new Node(array[m]);root.setLeft(helper(array, start, m - 1));root.setRight(helper(array, m + 1, end));return root;}

14.对于一颗完全二叉树,要求给所有节点加上一个pNext指针,指向同一层的相邻节点;如果当前节点已经是该层的最后一个节点,则将pNext指针指向NULL
运用队列,按层遍历,每次遍历一层时,添加新指针,由于每个节点只需要进队一次出队一次,时间复杂度为O(n),空间复杂度为O(n)

void addNextPoint(BinaryTreeNode* root){  if(root == NULL)return;  queue<BinaryTreeNode*> q;  q.push(root);  while(!q.empty()){    int levelLength = q.size();//当前层的节点个数    BinaryTreeNode* first = NULL,*second = NULL;//每次取两个元素进行操作    while(levelLength > 0){      first = q.front();      q.pop();      if(first->lchild)q.push(first->lchild);      if(first->rchild)q.push(first->rchild);      if(--levelLength == 0)break;      second = q.front();//第二个元素不需要出队      first->pNext = second;    }  }}

15. 给一个二叉树,每个节点都是正或负整数,如何找到一个子树,它所有节点的和最大后序遍历,每一个节点保存左右子树的和加上自己的值。额外一个空间存放最大值

static Node maxNode = new Node();//存放和最大的节点static int maxSum; //存放最大和public int getMaxValueNode(Node root) {int leftValue = 0, rightValue = 0, sum = 0;if (root.getLeft() != null) {leftValue = getMaxValueNode(root.getLeft());}if (root.getRight() != null) {rightValue = getMaxValueNode(root.getRight());}sum = leftValue + rightValue + root.getData();if (maxSum < sum) {maxSum = sum;maxNode = root;}return sum;}

16.输入两棵二叉树A和B,判断B是不是A的子结构

public boolean hasSubtree(Node<t> root1, Node<t> root2) {boolean result = false;if (root1 != null && root2 != null) {if (root1.getData() ==  root2.getData()) {result = doesTree1HaveTree2(root1, root2);}if (!result) {result = hasSubtree(root1.getLeftNode(), root2);}if (!result) {result = hasSubtree(root1.getRightNode(), root2);}}return result;}private boolean doesTree1HaveTree2(Node<t> root1, Node<t> root2) {if (root2 == null)  return true;if (root1 == null)  return false;if (root1.getData() != null && root2.getData() != null) {if (root1.getData() != root2.getData()) {return false;}}return doesTree1HaveTree2(root1.getLeftNode(), root2.getLeftNode()) && doesTree1HaveTree2(root1.getRightNode(), root2.getRightNode());}



0 0