以下是建立在后序遍历基础上的非递归代码:
1 /** 2 * Definition for a binary tree node. 3 * struct TreeNode { 4 * int val; 5 * TreeNode *left; 6 * TreeNode *right; 7 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8 * }; 9 */ 10 11 static int wing=[]() 12 { 13 std::ios::sync_with_stdio(false); 14 cin.tie(NULL); 15 return 0; 16 }(); 17 18 class Solution 19 { 20 public: 21 int minDepth(TreeNode* root) 22 { 23 if(root==NULL) 24 return 0; 25 stack<TreeNode*> s; 26 TreeNode* p=root; 27 TreeNode* r=NULL; 28 int count=INT_MAX; 29 while(p||!s.empty()) 30 { 31 if(p) 32 { 33 s.push(p); 34 p=p->left; 35 } 36 else 37 { 38 p=s.top(); 39 if(p->right&&p->right!=r) 40 { 41 p=p->right; 42 s.push(p); 43 p=p->left; 44 } 45 else 46 { 47 if(p->left==NULL&&p->right==NULL) 48 { 49 int k=s.size(); 50 count=min(count,k); 51 } 52 s.pop(); 53 r=p; 54 p=NULL; 55 } 56 } 57 } 58 return count; 59 } 60 };
下面是递归代码:
class Solution { public: int minDepth(TreeNode* root) { if(root==NULL) return 0; if(root->left==NULL) return 1+minDepth(root->right); if(root->right==NULL) return 1+minDepth(root->left); return 1+min(minDepth(root->left),minDepth(root->right)); } };
浙公网安备 33010602011771号