劍指offer(三十八)——二叉樹的深度

劍指offer(三十八)——二叉樹的深度

題目描述
輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。

題解
直接深度優先搜索(DFS)解決問題。

初始版

講道理,這代碼寫的有點爛,定義了全局變量還遞歸寫的也不咋地。我對遞歸也就這點認識(慚愧)。

	public int tree_deepth;
	
	public int TreeDepth(TreeNode root) {
        tree_deepth = 0;
        DFS(root, 0);
        return tree_deepth;
    }
	
	public void DFS(TreeNode root, int deepth) {
		if (root == null) {
			return;
		}
		deepth ++;
		if (tree_deepth < deepth) {
			tree_deepth = deepth;
		}
		if (root.right != null) {
			DFS(root.right, deepth);
		}
		if (root.left != null) {
			DFS(root.left, deepth);
		}
	}

優化一

  • 本函數遞歸+不用全局變量
  • 參考大佬寫法進行優化
  • 直接到達葉子節點進行返回,每一次返回深度加一,取最深的即可。圖示各層返回情況:
    在這裏插入圖片描述
	public int TreeDepth(TreeNode root) {
        if (root == null) {
			return 0;
		}
        int left = TreeDepth(root.left);
        int right = TreeDepth(root.right);
        return Math.max(left, right)+1;
    }

優化二

  • 非遞歸+不用全局變量
  • 其實就是層序遍歷了:
	public int TreeDepth(TreeNode root) {
        if (root == null) {
			return 0;
		}
        int depth = 0;
        Queue<TreeNode> queue = new LinkedList<TreeNode>();
        queue.add(root);
        while(!queue.isEmpty()) {
        	depth++;
        	//清除每一層的結點
        	int size = queue.size();
        	for(int i = 0; i < size; i++) {
        		TreeNode temp = queue.poll();
        		if (temp.right != null) {
					queue.add(temp.right);
				}
        		if (temp.left != null) {
					queue.add(temp.left);
				}
        	}
        }
        return depth;
    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章