java面試題:如何求二叉樹中節點的最大距離+層序遍歷
阿新 • • 發佈:2019-02-19
問題描述:求二叉樹中距離最遠的兩個 節點之間的距離。。
class Node{ public int data; public Node left; public Node right; public int leftMaxDistance; public int rightMaxDistance; public Node(int data){ this.data=data; this.left=null; this.right=null; } } public class BinaryTree{ private int maxLen=0; private Node root; public BinaryTree() { root=null; } private int max(int a,int b){ return a>b?a:b; } private void FindMaxDistance(Node root){ if(root==null) return ; if(root.left==null) root.leftMaxDistance=0; if(root.right==null) root.rightMaxDistance=0; if(root.left!=null) FindMaxDistance(root.left); if(root.right!=null) FindMaxDistance(root.right); if(root.left!=null){ root.leftMaxDistance=max(root.left.leftMaxDistance,root.left.leftMaxDistance)+1; } if(root.right!=null){ root.rightMaxDistance=max(root.right.rightMaxDistance,root.right.rightMaxDistance)+1; } if(root.leftMaxDistance+root.rightMaxDistance>maxLen){ maxLen=root.leftMaxDistance+root.rightMaxDistance; } } //向二叉排序樹插入節點 private void insertBtree(int data){ Node newNode=new Node(data); if(root==null){ root=newNode; }else{ Node current=root; Node parent; while(true){ parent=current; if(data<current.data){ current=current.left; if(current==null){ parent.left=newNode; return; } }else{ current=current.right; if(current==null){ parent.right=newNode; return; } } }//while } } //將數值輸入構建二叉樹 public void buildTree(int[] data){ for (int i = 0; i < data.length; i++) { insertBtree(data[i]); } }
//層序遍歷二叉樹 public void layerTranverse(){ if(this.root==null){ return; } Queue<Node> q=new LinkedList<Node>(); q.add(this.root); while(!q.isEmpty()){ Node n=q.poll(); System.out.print(n.data+" "); if(n.left!=null) q.add(n.left); if(n.right!=null) q.add(n.right); } } public static void main(String[] args) { int[] data={5,3,2,4,7,6,8}; BinaryTree bTree=new BinaryTree(); bTree.buildTree(data); bTree.FindMaxDistance(bTree.root); System.out.println(bTree.maxLen);
bTree.layerTranverse();
}
}