一个inorder traverse 的iteration:
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
res.add(curr.val);
curr = curr.right;
}
先循环左边,左边循环完循环右边,但是右边的node也要循环他的左边,所以要把循环左边的while循环和获得右边node的操作放在同一个循环里,外面再加一个循环,条件在!stack.isEmpty上增加curr!=NULL,这样获得右边node之后,先对右边node进行左循环,在从stack中获取右边node。
Lowest Common Ancester
class Solution {
public:
TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
if(root==NULL) return NULL;
else{
if(root==p) return root;
if(root==q) return root;
TreeNode* leftt = lowestCommonAncestor(root->left, p,q);
TreeNode* rightt = lowestCommonAncestor(root->right, p,q);
if(leftt==NULL&&rightt==NULL) return NULL;
if(leftt==NULL) return rightt;
if(rightt==NULL) return leftt;
return root;
}
}
};
计算p,q和他们的LCA,其实相当于计算p,q,和LCA的LCA,所以可以一层层循环对每个node找下去直到右边两边有一个有p,有一个有q,说明这个intermediate Node就是要找的LCA。
网友评论