【leetcode】Minimum Depth of Binary Tree

題目描述

Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

題目要求:
   求二叉樹的最短從根節點到葉子節點的深度,這道題與典型的求二叉樹的深度很相似,只是二叉樹的深度求的是最長,這道題求的是最短。

  
      對於上面這顆二叉樹,依次訪問從上向下遞歸訪問,對節點1來說,它左節點爲2,右節點爲3,對1節點最短深度來說,就是做已2爲節點的左子樹和以3爲節點的右子樹最小深度+1
     當遞歸到節點2時,其右子樹爲空,所以它的最小深度只可能來自左子樹,這樣不斷遞歸訪問子樹,當訪問到的節點爲空時,結束遞歸。
     根據上面的分析不難寫出下面的代碼

   
<pre name="code" class="cpp"> int run(TreeNode *root) {
        if (root == NULL)
		return 0;
        if(root->left==NULL & root->right!=NULL){
            return run(root->right) + 1;
        }
       if(root->left!=NULL & root->right==NULL){
            return run(root->left) + 1;
        }
		return min(run(root->left) + 1, run(root->right) + 1);
    }




  測試
       輸入上圖的二叉樹

  
#include<iostream>
using namespace std;

struct TreeNode {
	int val;
	TreeNode *left;
	TreeNode *right;
	TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

int min(int a, int b){
	return a < b ? a : b;
}
int minDepth(TreeNode *root) {
	if (root == NULL)
		return 0;
	if (root->left == NULL & root->right != NULL){
		return minDepth(root->right) + 1;
	}
	if (root->left != NULL & root->right == NULL){
		return minDepth(root->left) + 1;
	}
	return min(minDepth(root->left) + 1, minDepth(root->right) + 1);
}
int main(){
	TreeNode *node1 =new TreeNode(1);
	TreeNode *node2 = new TreeNode(2);
	TreeNode *node3 = new TreeNode(3);
	TreeNode *node4 = new TreeNode(4);
	TreeNode *node5 = new TreeNode(5);
	TreeNode *node6 = new TreeNode(6);
	node1->left = node2;
	node1->right = node3;
	node2->left = node4;
	node3->left = node5;
	node5->right = node6;
	cout << minDepth(node1) << endl;
	cin.get();
	return 0;
}

輸出
  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章