자바는 위에서 아래로 두 갈래 나무의 모든 노드를 출력하고 같은 층의 노드는 왼쪽에서 오른쪽으로 출력합니다.
                                            
 1452 단어  검지offer
                    
import java.util.ArrayList;
/*
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;
    public TreeNode(int val) {
        this.val = val;
    }
}*/
/**
 *  , 。
 * 
 * @author pomay
 *
 */
public class Solution_cengcibianli
{
	//  
	public ArrayList PrintFromTopToBottom(TreeNode root)
	{
		ArrayList printList = new ArrayList();
		ArrayList list = new ArrayList();
		if (root == null)
			return printList;
		list.add(root);
		//  , , , 
		for (int i = 0; i < list.size(); i++)
		{
			TreeNode node = list.get(i);
			if (node.left != null)
			{
				list.add(node.left);
			}
			if (node.right != null)
			{
				list.add(node.right);
			}
			printList.add(node.val);
		}
		return printList;
	}
	public static void main(String[] args)
	{
		TreeNode root = new TreeNode(8);
		root.left = new TreeNode(6);
		root.right = new TreeNode(10);
		root.left.left = new TreeNode(5);
		root.left.right = new TreeNode(7);
		root.right.left = new TreeNode(9);
		root.right.right = new TreeNode(11);
		Solution_cengcibianli s = new Solution_cengcibianli();
		ArrayList printList = new ArrayList();
		printList = s.PrintFromTopToBottom(root);
		for (int i = 0; i < printList.size(); i++)
		{
			System.out.print(printList.get(i) + " ");
		}
	}
}
       이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
20200326 - 검지offer 면접문제 27: 두 갈래 나무의 거울이솔 위 안에 28문제의 답안이 있는데 어떻게 꼬치는지 모르겠다.간단해....
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.