Binary Tree Inorder Traversal
Given a binary tree, return the inorder traversal of its nodes' values. 中序遍歷
Input: [1,null,2,3]
1
2
/
3
Output: [1,3,2]
解法
遞歸
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
vector<int> inorderTraversal(TreeNode *root) {
vector<int> res;
inorder(root, res);
return res;
}
void inorder(TreeNode *root, vector<int> &res) {
if (!root) return;
if (root->left) inorder(root->left, res);
res.push_back(root->val);
if (root->right) inorder(root->right, res);
}
};
非遞歸
用棧來代替遞歸,簡歷二叉樹指針棧,儲存所有的遍歷的二叉樹節(jié)點(diǎn)。每次儲存后,中序遍歷移動指針到當(dāng)前左子節(jié)點(diǎn),直到遍歷到最左側(cè)葉子節(jié)點(diǎn),對于最左側(cè)葉子節(jié)點(diǎn),取當(dāng)前節(jié)點(diǎn)值,并指針移動到當(dāng)前節(jié)點(diǎn)右子節(jié)點(diǎn),棧中刪除當(dāng)前節(jié)點(diǎn)。循環(huán)直到棧為空并且指針指向空節(jié)點(diǎn)。(有左邊,去左邊,沒左邊,打印當(dāng)前,去最右邊。)
class Solution {
public:
vector<int> inorderTraversal(TreeNode* root) {
vector<int> res;
stack<TreeNode* > s;
TreeNode* p = root;
while(p!= NULL || !s.empty()){
if (p!=NULL){
s.push(p);
p = p->left;
}else{
res.push_back(s.top()->val);
p = s.top()->right;
s.pop();
}
}
return res;
}
};
Maximum Depth of Binary Tree
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) return 0;
return max(maxDepth(root->left), maxDepth(root->right))+1;
}
};
Minimum Depth of Binary Tree
class Solution {
public:
int minDepth(TreeNode* root) {
if(root == NULL) return 0;
if (root->left == NULL && (root->right == NULL) ) return 1;
if (root->left == NULL) return minDepth(root->right)+1;
if (root->right == NULL) return minDepth(root->left)+1;
return min(minDepth(root->left), minDepth(root->right))+1;
}
};